10#include <userver/cache/cache_statistics.hpp>
11#include <userver/cache/caching_component_base.hpp>
12#include <userver/cache/mongo_cache_type_traits.hpp>
13#include <userver/components/component_context.hpp>
14#include <userver/formats/bson/document.hpp>
15#include <userver/formats/bson/inline.hpp>
16#include <userver/formats/bson/value_builder.hpp>
17#include <userver/storages/mongo/collection.hpp>
18#include <userver/storages/mongo/operations.hpp>
19#include <userver/storages/mongo/options.hpp>
20#include <userver/tracing/span.hpp>
21#include <userver/utils/cpu_relax.hpp>
22#include <userver/yaml_config/merge_schemas.hpp>
24USERVER_NAMESPACE_BEGIN
28inline const std::string kFetchAndParseStage =
"fetch_and_parse";
30inline constexpr std::chrono::milliseconds kCpuRelaxThreshold{10};
31inline constexpr std::chrono::milliseconds kCpuRelaxInterval{2};
35std::chrono::milliseconds GetMongoCacheUpdateCorrection(
const ComponentConfig&);
121template <
class MongoCacheTraits>
128 MongoCache(
const ComponentConfig&,
const ComponentContext&);
132 static yaml_config::Schema GetStaticConfigSchema();
137 const std::chrono::system_clock::time_point& last_update,
138 const std::chrono::system_clock::time_point& now,
139 cache::UpdateStatisticsScope& stats_scope
142 typename MongoCacheTraits::ObjectType DeserializeObject(
const formats::
bson::
Document& doc)
const;
146 const std::chrono::system_clock::time_point& last_update,
147 const std::chrono::system_clock::time_point& now,
148 const std::chrono::system_clock::duration& correction
151 std::unique_ptr<
typename MongoCacheTraits::DataType> GetData(cache::UpdateType type);
153 const std::shared_ptr<CollectionsType> mongo_collections_;
154 const storages::mongo::
Collection*
const mongo_collection_;
155 const std::chrono::system_clock::duration correction_;
156 std::size_t cpu_relax_iterations_{0};
159template <
class MongoCacheTraits>
160inline constexpr bool kHasValidate<MongoCache<MongoCacheTraits>> =
true;
162template <
class MongoCacheTraits>
163MongoCache<MongoCacheTraits>::MongoCache(
const ComponentConfig& config,
const ComponentContext& context)
165 mongo_collections_(context.FindComponent<
typename MongoCacheTraits::MongoCollectionsComponent>()
166 .
template GetCollectionForLibrary<CollectionsType>()),
167 mongo_collection_(std::addressof(mongo_collections_.get()->*MongoCacheTraits::kMongoCollectionsField)),
168 correction_(impl::GetMongoCacheUpdateCorrection(config)) {
169 [[maybe_unused]] mongo_cache::impl::CheckTraits<MongoCacheTraits> check_traits;
173 !mongo_cache::impl::kHasUpdateFieldName<MongoCacheTraits> &&
174 !mongo_cache::impl::kHasFindOperation<MongoCacheTraits>) {
175 throw std::logic_error(fmt::format(
176 "Incremental update support is requested in config but no update field "
177 "name is specified in traits of '{}' cache",
181 if (correction_.count() < 0) {
182 throw std::logic_error(fmt::format(
183 "Refusing to set forward (negative) update correction requested in "
184 "config for '{}' cache",
189 this->StartPeriodicUpdates();
192template <
class MongoCacheTraits>
194 this->StopPeriodicUpdates();
197template <
class MongoCacheTraits>
200 const std::chrono::system_clock::time_point& last_update,
201 const std::chrono::system_clock::time_point& now,
202 cache::UpdateStatisticsScope& stats_scope
204 namespace sm = storages::mongo;
206 const auto* collection = mongo_collection_;
207 auto find_op = GetFindOperation(type, last_update, now, correction_);
208 auto cursor = collection->Execute(find_op);
209 if (type == cache::UpdateType::kIncremental && !cursor) {
211 LOG_INFO() <<
"No changes in cache " << MongoCacheTraits::kName;
217 auto new_cache = GetData(type);
220 scope.Reset(kFetchAndParseStage);
223 std::size_t doc_count = 0;
225 for (
const auto& doc : cursor) {
230 stats_scope.IncreaseDocumentsReadCount(1);
233 auto object = DeserializeObject(doc);
234 auto key = (object.*MongoCacheTraits::kKeyField);
236 if (type == cache::UpdateType::kIncremental || new_cache->count(key) == 0) {
237 (*new_cache)[key] = std::move(object);
239 LOG_LIMITED_ERROR() <<
"Found duplicate key for 2 items in cache " << MongoCacheTraits::kName
242 }
catch (
const std::exception& e) {
243 LOG_LIMITED_ERROR() <<
"Failed to deserialize cache item of cache " << MongoCacheTraits::kName
244 <<
", _id=" << doc[
"_id"].
template ConvertTo<std::string>() <<
", what(): " << e;
245 stats_scope.IncreaseDocumentsParseFailures(1);
247 if (!MongoCacheTraits::kAreInvalidDocumentsSkipped)
throw;
251 const auto elapsed_time = scope.ElapsedTotal(kFetchAndParseStage);
252 if (elapsed_time > kCpuRelaxThreshold) {
253 cpu_relax_iterations_ =
254 static_cast<std::size_t>(
static_cast<
double>(doc_count) / (elapsed_time / kCpuRelaxInterval));
256 "Elapsed time for updating {} {} for {} data items is over threshold. "
257 "Will relax CPU every {} iterations",
259 elapsed_time.count(),
261 cpu_relax_iterations_
267 const auto size = new_cache->size();
268 this->Set(std::move(new_cache));
269 stats_scope.Finish(size);
272template <
class MongoCacheTraits>
273typename MongoCacheTraits::ObjectType
MongoCache<MongoCacheTraits>::DeserializeObject(
const formats::
bson::
Document& doc
275 if constexpr (mongo_cache::impl::kHasDeserializeObject<MongoCacheTraits>) {
276 return MongoCacheTraits::DeserializeObject(doc);
278 if constexpr (mongo_cache::impl::kHasDefaultDeserializeObject<MongoCacheTraits>) {
279 return doc.As<
typename MongoCacheTraits::ObjectType>();
281 UASSERT_MSG(
false,
"No deserialize operation defined but DeserializeObject invoked");
284template <
class MongoCacheTraits>
287 const std::chrono::system_clock::time_point& last_update,
288 const std::chrono::system_clock::time_point& now,
289 const std::chrono::system_clock::duration& correction
291 namespace bson = formats::
bson;
292 namespace sm = storages::mongo;
295 if constexpr (mongo_cache::impl::kHasFindOperation<MongoCacheTraits>) {
296 return MongoCacheTraits::GetFindOperation(type, last_update, now, correction);
298 if constexpr (mongo_cache::impl::kHasDefaultFindOperation<MongoCacheTraits>) {
300 if constexpr (mongo_cache::impl::kHasUpdateFieldName<MongoCacheTraits>) {
302 query_builder[MongoCacheTraits::kMongoUpdateFieldName] =
303 bson::MakeDoc(
"$gt", last_update - correction);
308 UASSERT_MSG(
false,
"No find operation defined but GetFindOperation invoked");
311 if (MongoCacheTraits::kIsSecondaryPreferred) {
317template <
class MongoCacheTraits>
318std::unique_ptr<
typename MongoCacheTraits::DataType>
MongoCache<MongoCacheTraits>::GetData(cache::UpdateType type) {
320 auto ptr =
this->Get();
321 return std::make_unique<
typename MongoCacheTraits::DataType>(*ptr);
323 return std::make_unique<
typename MongoCacheTraits::DataType>();
329std::string GetMongoCacheSchema();
333template <
class MongoCacheTraits>
336 impl::GetMongoCacheSchema()