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 {
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 ~PostgreCache() override;
453
454 static yaml_config::Schema GetStaticConfigSchema();
455
456private:
457 using CachedData = std::unique_ptr<DataType>;
458
459 UpdatedFieldType GetLastUpdated(std::chrono::system_clock::time_point last_update, const DataType& cache) const;
460
461 void Update(
462 cache::UpdateType type,
463 const std::chrono::system_clock::time_point& last_update,
464 const std::chrono::system_clock::time_point& now,
465 cache::UpdateStatisticsScope& stats_scope
466 ) override;
467
468 bool MayReturnNull() const override;
469
470 CachedData GetDataSnapshot(cache::UpdateType type, tracing::ScopeTime& scope);
471 void CacheResults(
472 storages::postgres::ResultSet res,
473 CachedData& data_cache,
474 cache::UpdateStatisticsScope& stats_scope,
475 tracing::ScopeTime& scope
476 );
477
478 static storages::postgres::Query GetAllQuery();
479 static storages::postgres::Query GetDeltaQuery();
480 static std::string GetWhereClause();
481 static std::string GetDeltaWhereClause();
482 static std::string GetOrderByClause();
483
484 std::chrono::milliseconds ParseCorrection(const ComponentConfig& config);
485
486 std::vector<storages::postgres::ClusterPtr> clusters_;
487
488 const std::chrono::system_clock::duration correction_;
489 const std::chrono::milliseconds full_update_timeout_;
490 const std::chrono::milliseconds incremental_update_timeout_;
491 const std::size_t chunk_size_;
492 const std::chrono::milliseconds sleep_between_chunks_;
493 std::size_t cpu_relax_iterations_parse_{0};
494 std::size_t cpu_relax_iterations_copy_{0};
495};
496
497template <typename PostgreCachePolicy>
498inline constexpr bool kHasValidate<PostgreCache<PostgreCachePolicy>> = true;
499
500template <typename PostgreCachePolicy>
501PostgreCache<PostgreCachePolicy>::PostgreCache(const ComponentConfig& config, const ComponentContext& context)
502 : BaseType{config, context},
503 correction_{ParseCorrection(config)},
504 full_update_timeout_{
505 config["full-update-op-timeout"].As<std::chrono::milliseconds>(pg_cache::detail::kDefaultFullUpdateTimeout)
506 },
507 incremental_update_timeout_{
508 config["incremental-update-op-timeout"]
509 .As<std::chrono::milliseconds>(pg_cache::detail::kDefaultIncrementalUpdateTimeout)
510 },
511 chunk_size_{config["chunk-size"].As<size_t>(pg_cache::detail::kDefaultChunkSize)},
512 sleep_between_chunks_{
513 config["sleep-between-chunks"].As<std::chrono::milliseconds>(pg_cache::detail::kDefaultSleepBetweenChunks)
514 }
515{
517 !chunk_size_ || storages::postgres::Portal::IsSupportedByDriver(),
518 "Either set 'chunk-size' to 0, or enable PostgreSQL portals by building "
519 "the framework with CMake option USERVER_FEATURE_PATCH_LIBPQ set to ON."
520 );
521
522 if (this->GetAllowedUpdateTypes() == cache::AllowedUpdateTypes::kFullAndIncremental && !kIncrementalUpdates) {
523 throw std::logic_error(
524 "Incremental update support is requested in config but no update field "
525 "name is specified in traits of '" +
526 config.Name() + "' cache"
527 );
528 }
529 if (correction_.count() < 0) {
530 throw std::logic_error(
531 "Refusing to set forward (negative) update correction requested in "
532 "config for '" +
533 config.Name() + "' cache"
534 );
535 }
536
537 const auto pg_alias = config["pgcomponent"].As<std::string>("");
538 if (pg_alias.empty()) {
539 throw storages::postgres::InvalidConfig{"No `pgcomponent` entry in configuration"};
540 }
541 auto& pg_cluster_comp = context.FindComponent<components::Postgres>(pg_alias);
542 const auto shard_count = pg_cluster_comp.GetShardCount();
543 clusters_.resize(shard_count);
544 for (size_t i = 0; i < shard_count; ++i) {
545 clusters_[i] = pg_cluster_comp.GetClusterForShard(i);
546 }
547
548 LOG_INFO()
549 << "Cache " << kName << " full update query `" << GetAllQuery().GetStatementView()
550 << "` incremental update query `" << GetDeltaQuery().GetStatementView() << "`";
551
552 this->StartPeriodicUpdates();
553}
554
555template <typename PostgreCachePolicy>
556PostgreCache<PostgreCachePolicy>::~PostgreCache() {
557 this->StopPeriodicUpdates();
558}
559
560template <typename PostgreCachePolicy>
561std::string PostgreCache<PostgreCachePolicy>::GetWhereClause() {
562 if constexpr (pg_cache::detail::kHasWhere<PostgreCachePolicy>) {
563 return fmt::format(FMT_COMPILE("where {}"), PostgreCachePolicy::kWhere);
564 } else {
565 return "";
566 }
567}
568
569template <typename PostgreCachePolicy>
570std::string PostgreCache<PostgreCachePolicy>::GetDeltaWhereClause() {
571 if constexpr (pg_cache::detail::kHasWhere<PostgreCachePolicy>) {
572 return fmt::format(
573 FMT_COMPILE("where ({}) and {} >= $1"),
574 PostgreCachePolicy::kWhere,
575 PostgreCachePolicy::kUpdatedField
576 );
577 } else {
578 return fmt::format(FMT_COMPILE("where {} >= $1"), PostgreCachePolicy::kUpdatedField);
579 }
580}
581
582template <typename PostgreCachePolicy>
583std::string PostgreCache<PostgreCachePolicy>::GetOrderByClause() {
584 if constexpr (pg_cache::detail::kHasOrderBy<PostgreCachePolicy>) {
585 return fmt::format(FMT_COMPILE("order by {}"), PostgreCachePolicy::kOrderBy);
586 } else {
587 return "";
588 }
589}
590
591template <typename PostgreCachePolicy>
592storages::postgres::Query PostgreCache<PostgreCachePolicy>::GetAllQuery() {
593 const storages::postgres::Query query = PolicyCheckerType::GetQuery();
594 return fmt::format("{} {} {}", query.GetStatementView(), GetWhereClause(), GetOrderByClause());
595}
596
597template <typename PostgreCachePolicy>
598storages::postgres::Query PostgreCache<PostgreCachePolicy>::GetDeltaQuery() {
599 if constexpr (kIncrementalUpdates) {
600 const storages::postgres::Query query = PolicyCheckerType::GetQuery();
601 return storages::postgres::Query{
602 fmt::format("{} {} {}", query.GetStatementView(), GetDeltaWhereClause(), GetOrderByClause()),
604 };
605 } else {
606 return GetAllQuery();
607 }
608}
609
610template <typename PostgreCachePolicy>
611std::chrono::milliseconds PostgreCache<PostgreCachePolicy>::ParseCorrection(const ComponentConfig& config) {
612 static constexpr std::string_view kUpdateCorrection = "update-correction";
613 if (pg_cache::detail::kHasCustomUpdated<PostgreCachePolicy> ||
614 this->GetAllowedUpdateTypes() == cache::AllowedUpdateTypes::kOnlyFull)
615 {
616 return config[kUpdateCorrection].As<std::chrono::milliseconds>(0);
617 } else {
618 return config[kUpdateCorrection].As<std::chrono::milliseconds>();
619 }
620}
621
622template <typename PostgreCachePolicy>
623typename PostgreCache<PostgreCachePolicy>::UpdatedFieldType PostgreCache<PostgreCachePolicy>::GetLastUpdated(
624 [[maybe_unused]] std::chrono::system_clock::time_point last_update,
625 const DataType& cache
626) const {
627 if constexpr (pg_cache::detail::kHasCustomUpdated<PostgreCachePolicy>) {
628 return PostgreCachePolicy::GetLastKnownUpdated(cache);
629 } else {
630 return UpdatedFieldType{last_update - correction_};
631 }
632}
633
634template <typename PostgreCachePolicy>
635void PostgreCache<PostgreCachePolicy>::Update(
636 cache::UpdateType type,
637 const std::chrono::system_clock::time_point& last_update,
638 const std::chrono::system_clock::time_point& /*now*/,
639 cache::UpdateStatisticsScope& stats_scope
640) {
641 namespace pg = storages::postgres;
642 if constexpr (!kIncrementalUpdates) {
644 }
645 const auto query = (type == cache::UpdateType::kFull) ? GetAllQuery() : GetDeltaQuery();
646 const std::chrono::milliseconds
647 timeout = (type == cache::UpdateType::kFull) ? full_update_timeout_ : incremental_update_timeout_;
648
649 // COPY current cached data
650 auto scope = tracing::Span::CurrentSpan().CreateScopeTime(std::string{pg_cache::detail::kCopyStage});
651 auto data_cache = GetDataSnapshot(type, scope);
652 [[maybe_unused]] const auto old_size = data_cache->size();
653
654 scope.Reset(std::string{pg_cache::detail::kFetchStage});
655
656 size_t changes = 0;
657 // Iterate clusters
658 for (auto& cluster : clusters_) {
659 if (chunk_size_ > 0) {
660 auto trx = cluster->Begin(
661 kClusterHostTypeFlags,
663 pg::CommandControl{timeout, pg_cache::detail::kStatementTimeoutOff}
664 );
665 auto portal = trx.MakePortal(query, GetLastUpdated(last_update, *data_cache));
666 while (portal) {
667 scope.Reset(std::string{pg_cache::detail::kFetchStage});
668 auto res = portal.Fetch(chunk_size_);
669 stats_scope.IncreaseDocumentsReadCount(res.Size());
670
671 scope.Reset(std::string{pg_cache::detail::kParseStage});
672 CacheResults(res, data_cache, stats_scope, scope);
673 changes += res.Size();
674 if (sleep_between_chunks_.count() > 0) {
675 engine::InterruptibleSleepFor(sleep_between_chunks_);
676 }
677 }
678 trx.Commit();
679 } else {
680 const bool has_parameter = query.GetStatementView().find('$') != std::string::npos;
681 auto res =
682 has_parameter
683 ? cluster->Execute(
684 kClusterHostTypeFlags,
685 pg::CommandControl{timeout, pg_cache::detail::kStatementTimeoutOff},
686 query,
687 GetLastUpdated(last_update, *data_cache)
688 )
689 : cluster->Execute(
690 kClusterHostTypeFlags,
691 pg::CommandControl{timeout, pg_cache::detail::kStatementTimeoutOff},
692 query
693 );
694 stats_scope.IncreaseDocumentsReadCount(res.Size());
695
696 scope.Reset(std::string{pg_cache::detail::kParseStage});
697 CacheResults(res, data_cache, stats_scope, scope);
698 changes += res.Size();
699 }
700 }
701
702 scope.Reset();
703
704 if constexpr (pg_cache::detail::kIsContainerCopiedByElement<DataType>) {
705 if (old_size > 0) {
706 const auto elapsed_copy = scope.ElapsedTotal(std::string{pg_cache::detail::kCopyStage});
707 if (elapsed_copy > pg_cache::detail::kCpuRelaxThreshold) {
708 cpu_relax_iterations_copy_ = static_cast<
709 std::size_t>(static_cast<double>(old_size) / (elapsed_copy / pg_cache::detail::kCpuRelaxInterval));
710 LOG_TRACE()
711 << "Elapsed time for copying " << kName << " " << elapsed_copy.count() << " for " << changes
712 << " data items is over threshold. Will relax CPU every " << cpu_relax_iterations_parse_
713 << " iterations";
714 }
715 }
716 }
717
718 if (changes > 0) {
719 const auto elapsed_parse = scope.ElapsedTotal(std::string{pg_cache::detail::kParseStage});
720 if (elapsed_parse > pg_cache::detail::kCpuRelaxThreshold) {
721 cpu_relax_iterations_parse_ = static_cast<
722 std::size_t>(static_cast<double>(changes) / (elapsed_parse / pg_cache::detail::kCpuRelaxInterval));
723 LOG_TRACE()
724 << "Elapsed time for parsing " << kName << " " << elapsed_parse.count() << " for " << changes
725 << " data items is over threshold. Will relax CPU every " << cpu_relax_iterations_parse_
726 << " iterations";
727 }
728 }
729 if (changes > 0 || type == cache::UpdateType::kFull) {
730 // Set current cache
731 pg_cache::detail::OnWritesDone(*data_cache);
732 stats_scope.Finish(data_cache->size());
733 this->Set(std::move(data_cache));
734 } else {
735 stats_scope.FinishNoChanges();
736 }
737}
738
739template <typename PostgreCachePolicy>
740bool PostgreCache<PostgreCachePolicy>::MayReturnNull() const {
741 return pg_cache::detail::MayReturnNull<PolicyType>();
742}
743
744template <typename PostgreCachePolicy>
745void PostgreCache<PostgreCachePolicy>::CacheResults(
746 storages::postgres::ResultSet res,
747 CachedData& data_cache,
748 cache::UpdateStatisticsScope& stats_scope,
749 tracing::ScopeTime& scope
750) {
751 auto values = res.AsSetOf<RawValueType>(storages::postgres::kRowTag);
752 utils::CpuRelax relax{cpu_relax_iterations_parse_, &scope};
753 for (auto p = values.begin(); p != values.end(); ++p) {
754 relax.Relax();
755 try {
756 using pg_cache::detail::CacheInsertOrAssign;
757 CacheInsertOrAssign(
758 *data_cache,
759 pg_cache::detail::ExtractValue<PostgreCachePolicy>(*p),
760 PostgreCachePolicy::kKeyMember
761 );
762 } catch (const std::exception& e) {
764 LOG_ERROR()
765 << "Error parsing data row in cache '" << kName << "' to '" << compiler::GetTypeName<ValueType>()
766 << "': " << e.what();
767 }
768 }
769}
770
771template <typename PostgreCachePolicy>
772typename PostgreCache<PostgreCachePolicy>::CachedData PostgreCache<
773 PostgreCachePolicy>::GetDataSnapshot(cache::UpdateType type, tracing::ScopeTime& scope) {
775 auto data = this->Get();
776 if (data) {
777 return pg_cache::detail::CopyContainer(*data, cpu_relax_iterations_copy_, scope);
778 }
779 }
780 return std::make_unique<DataType>();
781}
782
783namespace impl {
784
785std::string GetPostgreCacheSchema();
786
787} // namespace impl
788
789template <typename PostgreCachePolicy>
790yaml_config::Schema PostgreCache<PostgreCachePolicy>::GetStaticConfigSchema() {
791 using ParentType = typename pg_cache::detail::PolicyChecker<PostgreCachePolicy>::BaseType;
792 return yaml_config::MergeSchemas<ParentType>(impl::GetPostgreCacheSchema());
793}
794
795} // namespace components
796
797namespace utils::impl::projected_set {
798
799template <typename Set, typename Value, typename KeyMember>
800void CacheInsertOrAssign(Set& set, Value&& value, const KeyMember& /*key_member*/) {
801 DoInsert(set, std::forward<Value>(value));
802}
803
804} // namespace utils::impl::projected_set
805
806USERVER_NAMESPACE_END