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