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&);
120template <
class MongoCacheTraits>
122 using CollectionsType = mongo_cache::impl::CollectionsType<
decltype(MongoCacheTraits::kMongoCollectionsField)>;
125 static constexpr std::string_view kName = MongoCacheTraits::kName;
127 MongoCache(
const ComponentConfig&,
const ComponentContext&);
131 static yaml_config::Schema GetStaticConfigSchema();
136 const std::chrono::system_clock::time_point& last_update,
137 const std::chrono::system_clock::time_point& now,
138 cache::UpdateStatisticsScope& stats_scope
141 typename MongoCacheTraits::ObjectType DeserializeObject(
const formats::
bson::
Document& doc)
const;
145 const std::chrono::system_clock::time_point& last_update,
146 const std::chrono::system_clock::time_point& now,
147 const std::chrono::system_clock::duration& correction
150 std::unique_ptr<
typename MongoCacheTraits::DataType> GetData(
cache::
UpdateType type);
152 const std::shared_ptr<CollectionsType> mongo_collections_;
153 const storages::mongo::
Collection*
const mongo_collection_;
154 const std::chrono::system_clock::duration correction_;
155 std::size_t cpu_relax_iterations_{0};
158template <
class MongoCacheTraits>
159inline constexpr bool kHasValidate<MongoCache<MongoCacheTraits>> =
true;
161template <
class MongoCacheTraits>
162MongoCache<MongoCacheTraits>::MongoCache(
const ComponentConfig& config,
const ComponentContext& context)
164 mongo_collections_(context.FindComponent<
typename MongoCacheTraits::MongoCollectionsComponent>()
165 .
template GetCollectionForLibrary<CollectionsType>()),
166 mongo_collection_(std::addressof(mongo_collections_.get()->*MongoCacheTraits::kMongoCollectionsField)),
167 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>)
176 throw std::logic_error(fmt::format(
177 "Incremental update support is requested in config but no update field "
178 "name is specified in traits of '{}' cache",
182 if (correction_.count() < 0) {
183 throw std::logic_error(fmt::format(
184 "Refusing to set forward (negative) update correction requested in "
185 "config for '{}' cache",
190 this->StartPeriodicUpdates();
193template <
class MongoCacheTraits>
195 this->StopPeriodicUpdates();
198template <
class MongoCacheTraits>
201 const std::chrono::system_clock::time_point& last_update,
202 const std::chrono::system_clock::time_point& now,
203 cache::UpdateStatisticsScope& stats_scope
205 namespace sm = storages::mongo;
207 const auto* collection = mongo_collection_;
208 auto find_op = GetFindOperation(type, last_update, now, correction_);
209 auto cursor = collection->Execute(find_op);
212 LOG_INFO() <<
"No changes in cache " << MongoCacheTraits::kName;
218 auto new_cache = GetData(type);
221 scope.Reset(kFetchAndParseStage);
223 utils::
CpuRelax relax
{cpu_relax_iterations_
, &scope
};
224 std::size_t doc_count = 0;
226 for (
const auto& doc : cursor) {
234 auto object = DeserializeObject(doc);
235 auto key = (object.*MongoCacheTraits::kKeyField);
238 (*new_cache)[key] = std::move(object);
241 <<
"Found duplicate key for 2 items in cache " << MongoCacheTraits::kName <<
", key=" << key;
243 }
catch (
const std::exception& e) {
245 <<
"Failed to deserialize cache item of cache " << MongoCacheTraits::kName
246 <<
", _id=" << doc[
"_id"].
template ConvertTo<std::string>() <<
", what(): " << e;
249 if (!MongoCacheTraits::kAreInvalidDocumentsSkipped) {
255 const auto elapsed_time = scope.ElapsedTotal(kFetchAndParseStage);
256 if (elapsed_time > kCpuRelaxThreshold) {
257 cpu_relax_iterations_ =
static_cast<
258 std::size_t>(
static_cast<
double>(doc_count) / (elapsed_time / kCpuRelaxInterval));
260 "Elapsed time for updating {} {} for {} data items is over threshold. "
261 "Will relax CPU every {} iterations",
263 elapsed_time.count(),
265 cpu_relax_iterations_
271 const auto size = new_cache->size();
272 this->Set(std::move(new_cache));
276template <
class MongoCacheTraits>
279 if constexpr (mongo_cache::impl::kHasDeserializeObject<MongoCacheTraits>) {
280 return MongoCacheTraits::DeserializeObject(doc);
282 if constexpr (mongo_cache::impl::kHasDefaultDeserializeObject<MongoCacheTraits>) {
283 return doc.As<
typename MongoCacheTraits::ObjectType>();
285 UASSERT_MSG(
false,
"No deserialize operation defined but DeserializeObject invoked");
288template <
class MongoCacheTraits>
291 const std::chrono::system_clock::time_point& last_update,
292 const std::chrono::system_clock::time_point& now,
293 const std::chrono::system_clock::duration& correction
296 namespace sm = storages::mongo;
299 if constexpr (mongo_cache::impl::kHasFindOperation<MongoCacheTraits>) {
300 return MongoCacheTraits::GetFindOperation(type, last_update, now, correction);
302 if constexpr (mongo_cache::impl::kHasDefaultFindOperation<MongoCacheTraits>) {
304 if constexpr (mongo_cache::impl::kHasUpdateFieldName<MongoCacheTraits>) {
307 [MongoCacheTraits::kMongoUpdateFieldName] = bson
::MakeDoc("$gt", last_update - correction
);
312 UASSERT_MSG(
false,
"No find operation defined but GetFindOperation invoked");
315 if (MongoCacheTraits::kIsSecondaryPreferred) {
321template <
class MongoCacheTraits>
324 auto ptr =
this->Get();
325 return std::make_unique<
typename MongoCacheTraits::DataType>(*ptr);
327 return std::make_unique<
typename MongoCacheTraits::DataType>();
333std::string GetMongoCacheSchema();
337template <
class MongoCacheTraits>