6#include <userver/cache/base_postgres_cache_fwd.hpp>
12#include <unordered_map>
14#include <fmt/format.h>
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>
21#include <userver/storages/postgres/cluster.hpp>
22#include <userver/storages/postgres/component.hpp>
23#include <userver/storages/postgres/io/chrono.hpp>
25#include <userver/compiler/demangle.hpp>
26#include <userver/logging/log.hpp>
27#include <userver/tracing/span.hpp>
28#include <userver/utils/assert.hpp>
29#include <userver/utils/cpu_relax.hpp>
30#include <userver/utils/meta.hpp>
31#include <userver/utils/void_t.hpp>
32#include <userver/yaml_config/merge_schemas.hpp>
34USERVER_NAMESPACE_BEGIN
116namespace pg_cache::detail {
119using ValueType =
typename T::ValueType;
121inline constexpr bool kHasValueType = meta::kIsDetected<ValueType, T>;
124using RawValueTypeImpl =
typename T::RawValueType;
126inline constexpr bool kHasRawValueType = meta::kIsDetected<RawValueTypeImpl, T>;
128using RawValueType = meta::DetectedOr<ValueType<T>, RawValueTypeImpl, T>;
130template <
typename PostgreCachePolicy>
131auto ExtractValue(RawValueType<PostgreCachePolicy>&& raw) {
132 if constexpr (kHasRawValueType<PostgreCachePolicy>) {
133 return Convert(std::move(raw), formats::parse::To<ValueType<PostgreCachePolicy>>());
135 return std::move(raw);
141using HasNameImpl = std::enable_if_t<!std::string_view{T::kName}.empty()>;
143inline constexpr bool kHasName = meta::kIsDetected<HasNameImpl, T>;
147using HasQueryImpl =
decltype(T::kQuery);
149inline constexpr bool kHasQuery = meta::kIsDetected<HasQueryImpl, T>;
153using HasGetQueryImpl =
decltype(T::GetQuery());
155inline constexpr bool kHasGetQuery = meta::kIsDetected<HasGetQueryImpl, T>;
159using HasWhere =
decltype(T::kWhere);
161inline constexpr bool kHasWhere = meta::kIsDetected<HasWhere, T>;
165using HasUpdatedField =
decltype(T::kUpdatedField);
167inline constexpr bool kHasUpdatedField = meta::kIsDetected<HasUpdatedField, T>;
170using WantIncrementalUpdates = std::enable_if_t<!std::string_view{T::kUpdatedField}.empty()>;
172inline constexpr bool kWantIncrementalUpdates = meta::kIsDetected<WantIncrementalUpdates, T>;
176using KeyMemberTypeImpl = std::decay_t<std::invoke_result_t<
decltype(T::kKeyMember), ValueType<T>>>;
178inline constexpr bool kHasKeyMember = meta::kIsDetected<KeyMemberTypeImpl, T>;
180using KeyMemberType = meta::DetectedType<KeyMemberTypeImpl, T>;
183template <
typename T,
typename = USERVER_NAMESPACE::utils::void_t<>>
184struct DataCacheContainer {
186 meta::kIsStdHashable<KeyMemberType<T>>,
187 "With default CacheContainer, key type must be std::hash-able"
190 using type = std::unordered_map<KeyMemberType<T>, ValueType<T>>;
194struct DataCacheContainer<T, USERVER_NAMESPACE::utils::void_t<
typename T::CacheContainer>> {
195 using type =
typename T::CacheContainer;
199using DataCacheContainerType =
typename DataCacheContainer<T>::type;
204inline constexpr bool kIsContainerCopiedByElement =
205 meta::kIsInstantiationOf<std::unordered_map, T> || meta::kIsInstantiationOf<std::map, T>;
209CopyContainer(
const T& container, [[maybe_unused]] std::size_t cpu_relax_iterations, tracing::ScopeTime& scope) {
210 if constexpr (kIsContainerCopiedByElement<T>) {
211 auto copy = std::make_unique<T>();
212 if constexpr (meta::kIsReservable<T>) {
213 copy->reserve(container.size());
217 for (
const auto& kv : container) {
223 return std::make_unique<T>(container);
227template <
typename Container,
typename Value,
typename KeyMember,
typename... Args>
228void CacheInsertOrAssign(Container& container, Value&& value,
const KeyMember& key_member, Args&&... ) {
230 static_assert(
sizeof...(Args) == 0);
232 auto key = std::invoke(key_member, value);
233 container.insert_or_assign(std::move(key), std::forward<Value>(value));
237using HasOnWritesDoneImpl =
decltype(std::declval<T&>().OnWritesDone());
240void OnWritesDone(T& container) {
241 if constexpr (meta::kIsDetected<HasOnWritesDoneImpl, T>) {
242 container.OnWritesDone();
247using HasCustomUpdatedImpl =
decltype(T::GetLastKnownUpdated(std::declval<DataCacheContainerType<T>>()));
250inline constexpr bool kHasCustomUpdated = meta::kIsDetected<HasCustomUpdatedImpl, T>;
253using UpdatedFieldTypeImpl =
typename T::UpdatedFieldType;
255inline constexpr bool kHasUpdatedFieldType = meta::kIsDetected<UpdatedFieldTypeImpl, T>;
257using UpdatedFieldType = meta::DetectedOr<storages::postgres::TimePointTz, UpdatedFieldTypeImpl, T>;
260constexpr bool CheckUpdatedFieldType() {
261 if constexpr (kHasUpdatedFieldType<T>) {
262#if USERVER_POSTGRES_ENABLE_LEGACY_TIMESTAMP
264 std::is_same_v<
typename T::UpdatedFieldType, storages::postgres::TimePointTz> ||
265 std::is_same_v<
typename T::UpdatedFieldType, storages::postgres::TimePointWithoutTz> ||
266 std::is_same_v<
typename T::UpdatedFieldType, storages::postgres::TimePoint> || kHasCustomUpdated<T>,
267 "Invalid UpdatedFieldType, must be either TimePointTz or "
269 "or (legacy) system_clock::time_point"
273 std::is_same_v<
typename T::UpdatedFieldType, storages::
postgres::TimePointTz> ||
274 std::is_same_v<
typename T::UpdatedFieldType, storages::
postgres::TimePointWithoutTz> ||
275 kHasCustomUpdated<T>,
276 "Invalid UpdatedFieldType, must be either TimePointTz or "
282 !kWantIncrementalUpdates<T>,
283 "UpdatedFieldType must be explicitly specified when using "
284 "incremental updates"
292using HasClusterHostTypeImpl =
decltype(T::kClusterHostType);
295constexpr storages::
postgres::ClusterHostTypeFlags ClusterHostType() {
296 if constexpr (meta::kIsDetected<HasClusterHostTypeImpl, T>) {
297 return T::kClusterHostType;
299 return storages::postgres::ClusterHostType::kSlave;
305using HasMayReturnNull =
decltype(T::kMayReturnNull);
308constexpr bool MayReturnNull() {
309 if constexpr (meta::kIsDetected<HasMayReturnNull, T>) {
310 return T::kMayReturnNull;
316template <
typename PostgreCachePolicy>
317struct PolicyChecker {
319 static_assert(kHasName<PostgreCachePolicy>,
"The PosgreSQL cache policy must contain a static member `kName`");
320 static_assert(kHasValueType<PostgreCachePolicy>,
"The PosgreSQL cache policy must define a type alias `ValueType`");
322 kHasKeyMember<PostgreCachePolicy>,
323 "The PostgreSQL cache policy must contain a static member `kKeyMember` "
324 "with a pointer to a data or a function member with the object's key"
327 kHasQuery<PostgreCachePolicy> || kHasGetQuery<PostgreCachePolicy>,
328 "The PosgreSQL cache policy must contain a static data member "
329 "`kQuery` with a select statement or a static member function "
330 "`GetQuery` returning the query"
333 !(kHasQuery<PostgreCachePolicy> && kHasGetQuery<PostgreCachePolicy>),
334 "The PosgreSQL cache policy must define `kQuery` or "
335 "`GetQuery`, not both"
338 kHasUpdatedField<PostgreCachePolicy>,
339 "The PosgreSQL cache policy must contain a static member "
340 "`kUpdatedField`. If you don't want to use incremental updates, "
341 "please set its value to `nullptr`"
343 static_assert(CheckUpdatedFieldType<PostgreCachePolicy>());
346 ClusterHostType<PostgreCachePolicy>() & storages::postgres::kClusterHostRolesMask,
347 "Cluster host role must be specified for caching component, "
348 "please be more specific"
351 static storages::
postgres::Query GetQuery() {
352 if constexpr (kHasGetQuery<PostgreCachePolicy>) {
353 return PostgreCachePolicy::GetQuery();
355 return PostgreCachePolicy::kQuery;
359 using BaseType = CachingComponentBase<DataCacheContainerType<PostgreCachePolicy>>;
362inline constexpr std::chrono::minutes kDefaultFullUpdateTimeout{1};
363inline constexpr std::chrono::seconds kDefaultIncrementalUpdateTimeout{1};
364inline constexpr std::chrono::milliseconds kStatementTimeoutOff{0};
365inline constexpr std::chrono::milliseconds kCpuRelaxThreshold{10};
366inline constexpr std::chrono::milliseconds kCpuRelaxInterval{2};
368inline constexpr std::string_view kCopyStage =
"copy_data";
369inline constexpr std::string_view kFetchStage =
"fetch";
370inline constexpr std::string_view kParseStage =
"parse";
372inline constexpr std::size_t kDefaultChunkSize = 1000;
380template <
typename PostgreCachePolicy>
381class PostgreCache
final :
public pg_cache::detail::PolicyChecker<PostgreCachePolicy>::BaseType {
384 using PolicyType = PostgreCachePolicy;
385 using ValueType = pg_cache::detail::ValueType<PolicyType>;
386 using RawValueType = pg_cache::detail::RawValueType<PolicyType>;
387 using DataType = pg_cache::detail::DataCacheContainerType<PolicyType>;
388 using PolicyCheckerType = pg_cache::detail::PolicyChecker<PostgreCachePolicy>;
389 using UpdatedFieldType = pg_cache::detail::UpdatedFieldType<PostgreCachePolicy>;
390 using BaseType =
typename PolicyCheckerType::BaseType;
393 constexpr static bool kIncrementalUpdates = pg_cache::detail::kWantIncrementalUpdates<PolicyType>;
394 constexpr static auto kClusterHostTypeFlags = pg_cache::detail::ClusterHostType<PolicyType>();
395 constexpr static auto kName = PolicyType::kName;
397 PostgreCache(
const ComponentConfig&,
const ComponentContext&);
398 ~PostgreCache()
override;
400 static yaml_config::Schema GetStaticConfigSchema();
403 using CachedData = std::unique_ptr<DataType>;
405 UpdatedFieldType GetLastUpdated(std::chrono::system_clock::time_point last_update,
const DataType& cache)
const;
409 const std::chrono::system_clock::time_point& last_update,
410 const std::chrono::system_clock::time_point& now,
411 cache::UpdateStatisticsScope& stats_scope
414 bool MayReturnNull()
const override;
416 CachedData GetDataSnapshot(cache::UpdateType type, tracing::ScopeTime& scope);
419 CachedData& data_cache,
420 cache::UpdateStatisticsScope& stats_scope,
424 static storages::
postgres::Query GetAllQuery();
425 static storages::
postgres::Query GetDeltaQuery();
427 std::chrono::milliseconds ParseCorrection(
const ComponentConfig& config);
429 std::vector<storages::postgres::ClusterPtr> clusters_;
431 const std::chrono::system_clock::duration correction_;
432 const std::chrono::milliseconds full_update_timeout_;
433 const std::chrono::milliseconds incremental_update_timeout_;
434 const std::size_t chunk_size_;
435 std::size_t cpu_relax_iterations_parse_{0};
436 std::size_t cpu_relax_iterations_copy_{0};
439template <
typename PostgreCachePolicy>
440inline constexpr bool kHasValidate<PostgreCache<PostgreCachePolicy>> =
true;
442template <
typename PostgreCachePolicy>
443PostgreCache<PostgreCachePolicy>::PostgreCache(
const ComponentConfig& config,
const ComponentContext& context)
444 : BaseType{config, context},
445 correction_{ParseCorrection(config)},
446 full_update_timeout_{
447 config[
"full-update-op-timeout"].As<std::chrono::milliseconds>(pg_cache::detail::kDefaultFullUpdateTimeout)},
448 incremental_update_timeout_{config[
"incremental-update-op-timeout"].As<std::chrono::milliseconds>(
449 pg_cache::detail::kDefaultIncrementalUpdateTimeout
451 chunk_size_{config[
"chunk-size"].As<size_t>(pg_cache::detail::kDefaultChunkSize)} {
454 "Either set 'chunk-size' to 0, or enable PostgreSQL portals by building "
455 "the framework with CMake option USERVER_FEATURE_PATCH_LIBPQ set to ON."
459 throw std::logic_error(
460 "Incremental update support is requested in config but no update field "
461 "name is specified in traits of '" +
462 config.Name() +
"' cache"
465 if (correction_.count() < 0) {
466 throw std::logic_error(
467 "Refusing to set forward (negative) update correction requested in "
469 config.Name() +
"' cache"
473 const auto pg_alias = config[
"pgcomponent"].As<std::string>(
"");
474 if (pg_alias.empty()) {
477 auto& pg_cluster_comp = context.FindComponent<components::Postgres>(pg_alias);
478 const auto shard_count = pg_cluster_comp.GetShardCount();
479 clusters_.resize(shard_count);
480 for (size_t i = 0; i < shard_count; ++i) {
481 clusters_[i] = pg_cluster_comp.GetClusterForShard(i);
484 LOG_INFO() <<
"Cache " << kName <<
" full update query `" << GetAllQuery().Statement()
485 <<
"` incremental update query `" << GetDeltaQuery().Statement() <<
"`";
487 this->StartPeriodicUpdates();
490template <
typename PostgreCachePolicy>
491PostgreCache<PostgreCachePolicy>::~PostgreCache() {
492 this->StopPeriodicUpdates();
495template <
typename PostgreCachePolicy>
496storages::
postgres::Query PostgreCache<PostgreCachePolicy>::GetAllQuery() {
497 storages::
postgres::Query query = PolicyCheckerType::GetQuery();
498 if constexpr (pg_cache::detail::kHasWhere<PostgreCachePolicy>) {
499 return {fmt::format(
"{} where {}", query.Statement(), PostgreCachePolicy::kWhere), query.GetName()};
505template <
typename PostgreCachePolicy>
506storages::
postgres::Query PostgreCache<PostgreCachePolicy>::GetDeltaQuery() {
507 if constexpr (kIncrementalUpdates) {
508 storages::
postgres::Query query = PolicyCheckerType::GetQuery();
510 if constexpr (pg_cache::detail::kHasWhere<PostgreCachePolicy>) {
513 "{} where ({}) and {} >= $1",
515 PostgreCachePolicy::kWhere,
516 PolicyType::kUpdatedField
520 return {fmt::format(
"{} where {} >= $1", query.Statement(), PolicyType::kUpdatedField), query.GetName()};
523 return GetAllQuery();
527template <
typename PostgreCachePolicy>
528std::chrono::milliseconds PostgreCache<PostgreCachePolicy>::ParseCorrection(
const ComponentConfig& config) {
529 static constexpr std::string_view kUpdateCorrection =
"update-correction";
530 if (pg_cache::detail::kHasCustomUpdated<PostgreCachePolicy> ||
532 return config[kUpdateCorrection].As<std::chrono::milliseconds>(0);
534 return config[kUpdateCorrection].As<std::chrono::milliseconds>();
538template <
typename PostgreCachePolicy>
539typename PostgreCache<PostgreCachePolicy>::UpdatedFieldType PostgreCache<PostgreCachePolicy>::GetLastUpdated(
540 [[maybe_unused]] std::chrono::system_clock::time_point last_update,
541 const DataType& cache
543 if constexpr (pg_cache::detail::kHasCustomUpdated<PostgreCachePolicy>) {
544 return PostgreCachePolicy::GetLastKnownUpdated(cache);
546 return UpdatedFieldType{last_update - correction_};
550template <
typename PostgreCachePolicy>
551void PostgreCache<PostgreCachePolicy>::Update(
553 const std::chrono::system_clock::time_point& last_update,
554 const std::chrono::system_clock::time_point& ,
555 cache::UpdateStatisticsScope& stats_scope
558 if constexpr (!kIncrementalUpdates) {
562 const std::chrono::milliseconds timeout =
563 (type == cache::UpdateType::kFull) ? full_update_timeout_ : incremental_update_timeout_;
566 auto scope = tracing::Span::CurrentSpan().CreateScopeTime(std::string{pg_cache::detail::kCopyStage});
567 auto data_cache = GetDataSnapshot(type, scope);
568 [[maybe_unused]]
const auto old_size = data_cache->size();
570 scope.Reset(std::string{pg_cache::detail::kFetchStage});
574 for (
auto& cluster : clusters_) {
575 if (chunk_size_ > 0) {
576 auto trx = cluster->Begin(
577 kClusterHostTypeFlags,
579 pg::CommandControl{timeout, pg_cache::detail::kStatementTimeoutOff}
581 auto portal = trx.MakePortal(query, GetLastUpdated(last_update, *data_cache));
583 scope.Reset(std::string{pg_cache::detail::kFetchStage});
584 auto res = portal.Fetch(chunk_size_);
585 stats_scope.IncreaseDocumentsReadCount(res.Size());
587 scope.Reset(std::string{pg_cache::detail::kParseStage});
588 CacheResults(res, data_cache, stats_scope, scope);
589 changes += res.Size();
593 bool has_parameter = query.Statement().find(
'$') != std::string::npos;
594 auto res = has_parameter ? cluster->Execute(
595 kClusterHostTypeFlags,
596 pg::CommandControl{timeout, pg_cache::detail::kStatementTimeoutOff},
598 GetLastUpdated(last_update, *data_cache)
601 kClusterHostTypeFlags,
602 pg::CommandControl{timeout, pg_cache::detail::kStatementTimeoutOff},
605 stats_scope.IncreaseDocumentsReadCount(res.Size());
607 scope.Reset(std::string{pg_cache::detail::kParseStage});
608 CacheResults(res, data_cache, stats_scope, scope);
609 changes += res.Size();
615 if constexpr (pg_cache::detail::kIsContainerCopiedByElement<DataType>) {
617 const auto elapsed_copy = scope.ElapsedTotal(std::string{pg_cache::detail::kCopyStage});
618 if (elapsed_copy > pg_cache::detail::kCpuRelaxThreshold) {
619 cpu_relax_iterations_copy_ =
static_cast<std::size_t>(
620 static_cast<
double>(old_size) / (elapsed_copy / pg_cache::detail::kCpuRelaxInterval)
622 LOG_TRACE() <<
"Elapsed time for copying " << kName <<
" " << elapsed_copy.count() <<
" for " << changes
623 <<
" data items is over threshold. Will relax CPU every " << cpu_relax_iterations_parse_
630 const auto elapsed_parse = scope.ElapsedTotal(std::string{pg_cache::detail::kParseStage});
631 if (elapsed_parse > pg_cache::detail::kCpuRelaxThreshold) {
632 cpu_relax_iterations_parse_ =
static_cast<std::size_t>(
633 static_cast<
double>(changes) / (elapsed_parse / pg_cache::detail::kCpuRelaxInterval)
635 LOG_TRACE() <<
"Elapsed time for parsing " << kName <<
" " << elapsed_parse.count() <<
" for " << changes
636 <<
" data items is over threshold. Will relax CPU every " << cpu_relax_iterations_parse_
640 if (changes > 0 || type == cache::UpdateType::kFull) {
642 pg_cache::detail::OnWritesDone(*data_cache);
643 stats_scope.Finish(data_cache->size());
644 this->Set(std::move(data_cache));
650template <
typename PostgreCachePolicy>
651bool PostgreCache<PostgreCachePolicy>::MayReturnNull()
const {
652 return pg_cache::detail::MayReturnNull<PolicyType>();
655template <
typename PostgreCachePolicy>
656void PostgreCache<PostgreCachePolicy>::CacheResults(
658 CachedData& data_cache,
659 cache::UpdateStatisticsScope& stats_scope,
662 auto values = res.AsSetOf<RawValueType>(storages::postgres::kRowTag);
664 for (
auto p = values.begin(); p != values.end(); ++p) {
667 using pg_cache::detail::CacheInsertOrAssign;
669 *data_cache, pg_cache::detail::ExtractValue<PostgreCachePolicy>(*p), PostgreCachePolicy::kKeyMember
671 }
catch (
const std::exception& e) {
672 stats_scope.IncreaseDocumentsParseFailures(1);
673 LOG_ERROR() <<
"Error parsing data row in cache '" << kName <<
"' to '"
674 << compiler::GetTypeName<ValueType>() <<
"': " << e.what();
679template <
typename PostgreCachePolicy>
680typename PostgreCache<PostgreCachePolicy>::CachedData
683 auto data =
this->Get();
685 return pg_cache::detail::CopyContainer(*data, cpu_relax_iterations_copy_, scope);
688 return std::make_unique<DataType>();
693std::string GetPostgreCacheSchema();
697template <
typename PostgreCachePolicy>
698yaml_config::Schema PostgreCache<PostgreCachePolicy>::GetStaticConfigSchema() {
699 using ParentType =
typename pg_cache::detail::PolicyChecker<PostgreCachePolicy>::BaseType;
700 return yaml_config::MergeSchemas<ParentType>(impl::GetPostgreCacheSchema());
705namespace utils::impl::projected_set {
707template <
typename Set,
typename Value,
typename KeyMember>
708void CacheInsertOrAssign(Set& set, Value&& value,
const KeyMember& ) {
709 DoInsert(set, std::forward<Value>(value));