userver: userver/dynamic_config/snapshot.hpp Source File
Loading...
Searching...
No Matches
snapshot.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/dynamic_config/snapshot.hpp
4/// @brief @copybrief dynamic_config::Snapshot
5
6#include <any>
7#include <cstddef>
8#include <cstdint>
9#include <string>
10#include <string_view>
11#include <type_traits>
12#include <utility>
13#include <vector>
14
15#include <userver/compiler/impl/lifetime.hpp>
16#include <userver/dynamic_config/impl/snapshot.hpp>
17#include <userver/dynamic_config/impl/to_json.hpp>
18#include <userver/dynamic_config/registered_config_meta.hpp>
19#include <userver/formats/json_fwd.hpp>
20#include <userver/utils/fast_pimpl.hpp>
21
22USERVER_NAMESPACE_BEGIN
23
24namespace dynamic_config {
25
26/// Opaque schema hash supplied by code generation. userver does not calculate it.
27struct SchemaHash final {
28 constexpr SchemaHash() = default;
29
30 constexpr explicit SchemaHash(std::string_view value)
31 : value(value)
32 {}
33
34 std::string_view value;
35};
36
37/// A strong typedef for usage in dynamic_config::Key constructors.
38struct DefaultAsJsonString final {
39 constexpr explicit DefaultAsJsonString(std::string_view json_string);
40
41 std::string_view json_string;
42};
43
44/// @brief Explicitly opts out of schema hash metadata for a config item.
45/// Use only when the selected config source discovers configs by name and
46/// supports missing schema hashes, or for local tests. The standard
47/// @ref components::DynamicConfigClientUpdater supports this path.
48/// @warning An updater that skips registrations with an empty
49/// @ref dynamic_config::RegisteredConfigMeta::schema_hash will not subscribe to
50/// this item. Prefer a generated @ref dynamic_config::Key or pass the same
51/// config's generated `GetSchemaHash()` result to a handwritten key.
52/// @see @ref dynamic_config_schema_hash for checking a source's contract.
53struct NoSchemaHash final {
54 constexpr explicit NoSchemaHash() = default;
55};
56
57/// A config name-value pair for usage in dynamic_config::Key constructors.
58struct ConfigDefault final {
59#ifndef ARCADIA_ROOT
60 /// @deprecated Pass a generated @ref dynamic_config::SchemaHash with a JSON
61 /// default, or explicitly opt out using @ref dynamic_config::NoSchemaHash.
62 template <typename T>
63 [[deprecated(
64 "Missing config schema hash. Use dynamic config code generation. "
65 "Schema-based config sources may omit this config from subscriptions, leaving it at its default value. "
66 "Use NoSchemaHash{} only when intentionally targeting a config source that supports hashless configs, "
67 "such as open-source integrations or tests."
68 )]]
69 ConfigDefault(std::string_view name, const T& value);
70#endif
71
72 /// @brief Creates a typed default explicitly omitting schema hash metadata.
73 template <typename T, typename Tag>
74 requires std::is_same_v<Tag, NoSchemaHash>
75 ConfigDefault(std::string_view name, const T& value, Tag);
76
77#ifndef ARCADIA_ROOT
78 /// @deprecated Pass a generated @ref dynamic_config::SchemaHash, or
79 /// explicitly opt out using @ref dynamic_config::NoSchemaHash.
80 [[deprecated(
81 "Missing config schema hash. Use dynamic config code generation. "
82 "Schema-based config sources may omit this config from subscriptions, leaving it at its default value. "
83 "Use NoSchemaHash{} only when intentionally targeting a config source that supports hashless configs, "
84 "such as open-source integrations or tests."
85 )]]
86 ConfigDefault(std::string_view name, DefaultAsJsonString default_json);
87#endif
88
89 /// @brief Creates a JSON default explicitly omitting schema hash metadata.
90 template <typename Tag>
91 requires std::is_same_v<Tag, NoSchemaHash>
92 ConfigDefault(std::string_view name, DefaultAsJsonString default_json, Tag);
93
94 /// @warning The schema hash must be supplied by code generation. userver
95 /// treats it as an opaque value and does not calculate it.
96 ConfigDefault(std::string_view name, DefaultAsJsonString default_json, SchemaHash schema_hash);
97
98 std::string_view name;
99 std::string default_json;
100 std::string schema_hash;
101};
102
103/// A tag type for usage in dynamic_config::Key constructors.
104struct ConstantConfig final {
105 constexpr explicit ConstantConfig() = default;
106};
107
108/// @brief A config key is a unique identifier for a config variable
109/// @see @ref dynamic_config_key for declarations with schema metadata.
110template <typename Variable>
111class Key final {
112public:
113 /// The type of the parsed config variable.
114 using VariableType = Variable;
115
116 using JsonParser = Variable (*)(const formats::json::Value&);
117 using DocsMapParser = Variable (*)(const DocsMap&);
118
119#ifndef ARCADIA_ROOT
120 /// @brief The constructor for a trivial `VariableType`, e.g. `bool`, integer,
121 /// `double`, `string`. The default is passed by value.
122 ///
123 /// @deprecated Pass a generated @ref dynamic_config::SchemaHash, or
124 /// explicitly opt out using @ref dynamic_config::NoSchemaHash.
125 [[deprecated(
126 "Missing config schema hash. Use dynamic config code generation. "
127 "Schema-based config sources may omit this config from subscriptions, leaving it at its default value. "
128 "Use NoSchemaHash{} only when intentionally targeting a config source that supports hashless configs, "
129 "such as open-source integrations or tests."
130 )]]
131 Key(std::string_view name, const VariableType& default_value);
132#endif
133
134 /// @brief Creates a key with a typed default explicitly omitting schema
135 /// hash metadata. See @ref dynamic_config::NoSchemaHash for source requirements.
136 /// @snippet core/src/dynamic_config/config_test.cpp key bool
137 template <typename Tag>
138 requires std::is_same_v<Tag, NoSchemaHash>
139 Key(std::string_view name, const VariableType& default_value, Tag);
140
141 /// @brief The constructor for a trivial `VariableType` with schema
142 /// metadata.
143 /// @param schema_hash Opaque schema hash.
144 /// @warning The schema hash must be supplied by code generation. userver
145 /// treats it as an opaque value and does not calculate it.
146 Key(std::string_view name, const VariableType& default_value, SchemaHash schema_hash);
147
148#ifndef ARCADIA_ROOT
149 /// @brief The constructor for a non-trivial `VariableType`. The default is
150 /// passed as a JSON string.
151 ///
152 /// Uses formats::json::Value `Parse` customization point function to parse
153 /// `VariableType`.
154 ///
155 /// @deprecated Pass a generated @ref dynamic_config::SchemaHash, or
156 /// explicitly opt out using @ref dynamic_config::NoSchemaHash.
157 [[deprecated(
158 "Missing config schema hash. Use dynamic config code generation. "
159 "Schema-based config sources may omit this config from subscriptions, leaving it at its default value. "
160 "Use NoSchemaHash{} only when intentionally targeting a config source that supports hashless configs, "
161 "such as open-source integrations or tests."
162 )]]
163 Key(std::string_view name, DefaultAsJsonString default_json);
164#endif
165
166 /// @brief Creates a key with a JSON default explicitly omitting schema hash
167 /// metadata. Uses the @ref formats::json::Value `Parse` customization point.
168 /// @snippet core/src/dynamic_config/config_test.cpp struct config cpp
169 template <typename Tag>
170 requires std::is_same_v<Tag, NoSchemaHash>
171 Key(std::string_view name, DefaultAsJsonString default_json, Tag);
172
173 /// @brief The constructor for a non-trivial `VariableType` with schema
174 /// metadata.
175 /// @param schema_hash Opaque schema hash.
176 /// @warning The schema hash must be supplied by code generation. userver
177 /// treats it as an opaque value and does not calculate it.
178 /// @snippet core/src/cache/cache_config.cpp key with schema hash
179 Key(std::string_view name, DefaultAsJsonString default_json, SchemaHash schema_hash);
180
181#ifndef ARCADIA_ROOT
182 /// @brief The constructor that provides a special parser from JSON.
183 /// @warning Prefer the constructors above whenever possible.
184 /// @details Can be used when generic `Parse` is not applicable. Sometimes
185 /// used to add validation, e.g. minimum, maximum, string pattern, etc.
186 /// @deprecated Pass a generated @ref dynamic_config::SchemaHash, or
187 /// explicitly opt out using @ref dynamic_config::NoSchemaHash.
188 [[deprecated(
189 "Missing config schema hash. Use dynamic config code generation. "
190 "Schema-based config sources may omit this config from subscriptions, leaving it at its default value. "
191 "Use NoSchemaHash{} only when intentionally targeting a config source that supports hashless configs, "
192 "such as open-source integrations or tests."
193 )]]
194 Key(std::string_view name, JsonParser parser, DefaultAsJsonString default_json);
195#endif
196
197 /// @brief Creates a key with a custom JSON parser explicitly omitting schema
198 /// hash metadata. See @ref dynamic_config::NoSchemaHash for source requirements.
199 template <typename Tag>
200 requires std::is_same_v<Tag, NoSchemaHash>
201 Key(std::string_view name, JsonParser parser, DefaultAsJsonString default_json, Tag);
202
203 /// @brief The constructor with a custom JSON parser and schema metadata.
204 /// @param name config variable name
205 /// @param parser custom JSON parser for the variable
206 /// @param default_json default value as a JSON string
207 /// @param schema_hash Opaque schema hash.
208 /// Stored in the global registry and retrievable via
209 /// dynamic_config::impl::GetRegisteredConfigsMeta() as
210 /// dynamic_config::RegisteredConfigMeta::schema_hash.
211 /// @warning The schema hash must be supplied by code generation. userver
212 /// treats it as an opaque value and does not calculate it.
213 Key(std::string_view name, JsonParser parser, DefaultAsJsonString default_json, SchemaHash schema_hash);
214
215 /// @brief The constructor that parses multiple JSON config items
216 /// into a single C++ object.
217 ///
218 /// To register schema metadata for the JSON config items, pass the generated
219 /// `variable_namespace::GetSchemaHash()` to each ConfigDefault.
220 /// @warning Prefer to use a separate `Key` per JSON config item and use the
221 /// constructors above whenever possible.
222 template <std::size_t N>
223 Key(DocsMapParser parser, const ConfigDefault (&default_json_map)[N]);
224
225 /// Creates a config that always has the same value.
226 Key(ConstantConfig, VariableType value);
227
228 /// @cond
229 Key(impl::InternalTag, std::string_view name);
230
231 Key(impl::InternalTag, DocsMapParser parser);
232 /// @endcond
233
234 Key(const Key&) noexcept = delete;
235 Key& operator=(const Key&) noexcept = delete;
236
237 /// @returns the name of the single registered config item, or the explicit
238 /// name of an internal derived key. Calling this for a key with zero or
239 /// multiple config items and no explicit internal name is an invariant violation.
240 std::string_view GetName() const noexcept;
241
242 /// Parses the config. Useful only in some very niche scenarios. The config
243 /// value should be typically be retrieved from dynamic_config::Snapshot,
244 /// which is obtained from components::DynamicConfig in production or from
245 /// dynamic_config::StorageMock in unit tests.
246 VariableType Parse(const DocsMap& docs_map) const;
247
248private:
249 friend struct impl::ConfigIdGetter;
250
251 const impl::ConfigId id_;
252};
253
254/// @brief The shared snapshot of
255/// @ref scripts/docs/en/userver/dynamic_config.md "dynamic configs". Cheap to
256/// copy, even cheaper to move. Thread safe, not updated with new dynamic
257/// config values in background (it's a snapshot!).
258///
259/// When a config update comes in via new `DocsMap`, configs of all
260/// the registered types are constructed and stored in `Config`. After that
261/// the `DocsMap` is dropped.
262///
263/// Config types are automatically registered if they are used
264/// somewhere in the program.
265///
266/// ## Usage example:
267/// @snippet core/src/components/component_sample_test.cpp Sample user component runtime config read
268class Snapshot final {
269public:
270 Snapshot(const Snapshot&);
271 Snapshot& operator=(const Snapshot&);
272
273 Snapshot(Snapshot&&) noexcept;
274 Snapshot& operator=(Snapshot&&) noexcept;
275
276 ~Snapshot();
277
278 /// Used to access individual configs in the type-safe config map
279 template <typename VariableType>
280 const VariableType& operator[](const Key<VariableType>& key) const& USERVER_IMPL_LIFETIME_BOUND;
281
282 /// Used to access individual configs in the type-safe config map
283 template <typename VariableType>
284 const VariableType& operator[](const Key<VariableType>&) &&;
285
286private:
287 // for the constructor
288 friend class Source;
289 friend class impl::StorageData;
290 friend struct Diff;
291
292 explicit Snapshot(const impl::StorageData& storage);
293
294 const impl::SnapshotData& GetData() const;
295
296 struct Impl;
297 utils::FastPimpl<Impl, 16, 8> impl_;
298};
299
300// ========================== Implementation follows ==========================
301
302constexpr DefaultAsJsonString::DefaultAsJsonString(std::string_view json_string)
303 : json_string(json_string)
304{}
305
306#ifndef ARCADIA_ROOT
307template <typename T>
308ConfigDefault::ConfigDefault(std::string_view name, const T& value)
309 : ConfigDefault(name, value, NoSchemaHash{})
310{}
311#endif
312
313template <typename T, typename Tag>
314requires std::is_same_v<Tag, NoSchemaHash>
315ConfigDefault::ConfigDefault(std::string_view name, const T& value, Tag)
316 : name(name),
317 default_json(impl::ToJsonString(value))
318{}
319
320template <typename Tag>
321requires std::is_same_v<Tag, NoSchemaHash>
322ConfigDefault::ConfigDefault(std::string_view name, DefaultAsJsonString default_json, Tag)
323 : ConfigDefault(name, default_json, SchemaHash{})
324{}
325
326#ifndef ARCADIA_ROOT
327template <typename Variable>
328Key<Variable>::Key(std::string_view name, const VariableType& default_value)
329 : Key(name, default_value, NoSchemaHash{})
330{}
331#endif
332
333template <typename Variable>
334template <typename Tag>
335requires std::is_same_v<Tag, NoSchemaHash>
336Key<Variable>::Key(std::string_view name, const VariableType& default_value, Tag)
337 : Key(name, default_value, SchemaHash{})
338{}
339
340template <typename Variable>
341Key<Variable>::Key(std::string_view name, const VariableType& default_value, SchemaHash schema_hash)
342 : id_(impl::Register(
343 [name = std::string{name}](const auto& docs_map) -> std::any {
344 return impl::DocsMapGet(docs_map, name).template As<VariableType>();
345 },
346 {{.name = std::string{name},
347 .schema_hash = std::string{schema_hash.value},
348 .default_as_json_string = impl::ToJsonString(default_value)}}
349 ))
350{}
351
352#ifndef ARCADIA_ROOT
353template <typename Variable>
354Key<Variable>::Key(std::string_view name, DefaultAsJsonString default_json)
355 : Key(name, default_json, NoSchemaHash{})
356{}
357#endif
358
359template <typename Variable>
360template <typename Tag>
361requires std::is_same_v<Tag, NoSchemaHash>
362Key<Variable>::Key(std::string_view name, DefaultAsJsonString default_json, Tag)
363 : Key(name, default_json, SchemaHash{})
364{}
365
366template <typename Variable>
367Key<Variable>::Key(std::string_view name, DefaultAsJsonString default_json, SchemaHash schema_hash)
368 : id_(impl::Register(
369 [name = std::string{name}](const auto& docs_map) -> std::any {
370 return impl::DocsMapGet(docs_map, name).template As<VariableType>();
371 },
372 {{.name = std::string{name},
373 .schema_hash = std::string{schema_hash.value},
374 .default_as_json_string = std::string{default_json.json_string}}}
375 ))
376{}
377
378#ifndef ARCADIA_ROOT
379template <typename Variable>
380Key<Variable>::Key(std::string_view name, JsonParser parser, DefaultAsJsonString default_json)
381 : Key(name, parser, default_json, NoSchemaHash{})
382{}
383#endif
384
385template <typename Variable>
386template <typename Tag>
387requires std::is_same_v<Tag, NoSchemaHash>
388Key<Variable>::Key(std::string_view name, JsonParser parser, DefaultAsJsonString default_json, Tag)
389 : Key(name, parser, default_json, SchemaHash{})
390{}
391
392template <typename Variable>
393Key<Variable>::Key(std::string_view name, JsonParser parser, DefaultAsJsonString default_json, SchemaHash schema_hash)
394 : id_(impl::Register(
395 [name = std::string{name}, parser](const auto& docs_map) -> std::any {
396 return parser(impl::DocsMapGet(docs_map, name));
397 },
398 {{.name = std::string{name},
399 .schema_hash = std::string{schema_hash.value},
400 .default_as_json_string = std::string{default_json.json_string}}}
401 ))
402{}
403
404template <typename Variable>
405template <std::size_t N>
406Key<Variable>::Key(DocsMapParser parser, const ConfigDefault (&default_json_map)[N])
407 : id_([parser, &default_json_map] {
408 std::vector<impl::ConfigMetadata> config_metadata;
409 config_metadata.reserve(N);
410 for (const auto& config_default : default_json_map) {
411 config_metadata.push_back({
412 .name = std::string{config_default.name},
413 .schema_hash = config_default.schema_hash,
414 .default_as_json_string = config_default.default_json,
415 });
416 }
417 return impl::Register(
418 [parser](const DocsMap& docs_map) -> std::any { return parser(docs_map); },
419 std::move(config_metadata)
420 );
421 }())
422{}
423
424template <typename Variable>
425Key<Variable>::Key(ConstantConfig /*tag*/, VariableType value)
426 : id_(impl::Register([value = std::move(value)](const DocsMap& /*unused*/) { return value; }, {}))
427{}
428
429template <typename Variable>
430Key<Variable>::Key(impl::InternalTag, std::string_view name)
431 : id_(impl::RegisterInternal(
432 std::string{name},
433 [name = std::string{name}](const auto& docs_map) -> std::any {
434 return impl::DocsMapGet(docs_map, name).template As<VariableType>();
435 }
436 ))
437{}
438
439template <typename Variable>
440Key<Variable>::Key(impl::InternalTag, DocsMapParser parser)
441 : id_(impl::RegisterInternal(
442 std::string{},
443 [parser](const DocsMap& docs_map) -> std::any { return parser(docs_map); }
444 ))
445{}
446
447template <typename VariableType>
448std::string_view Key<VariableType>::GetName() const noexcept {
449 return impl::GetName(id_);
450}
451
452template <typename VariableType>
453VariableType Key<VariableType>::Parse(const DocsMap& docs_map) const {
454 return std::any_cast<VariableType>(impl::MakeConfig(id_, docs_map));
455}
456
457template <typename VariableType>
458const VariableType& Snapshot::operator[](const Key<VariableType>& key) const& USERVER_IMPL_LIFETIME_BOUND {
459 return GetData().Get<VariableType>(impl::ConfigIdGetter::Get(key));
460}
461
462template <typename VariableType>
463const VariableType& Snapshot::operator[](const Key<VariableType>&) && {
464 static_assert(!sizeof(VariableType), "keep the Snapshot before using, please");
465}
466
467} // namespace dynamic_config
468
469USERVER_NAMESPACE_END