userver: userver/dynamic_config/source.hpp Source File
Loading...
Searching...
No Matches
source.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/dynamic_config/source.hpp
4/// @brief @copybrief dynamic_config::Source
5
6#include <optional>
7#include <string_view>
8#include <utility>
9
10#include <userver/compiler/impl/lifetime.hpp>
11#include <userver/concurrent/async_event_source.hpp>
12#include <userver/dynamic_config/snapshot.hpp>
13#include <userver/utils/assert.hpp>
14#include <userver/utils/resource_scopes_fwd.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace components {
19class DynamicConfig;
20}
21
22namespace dynamic_config {
23
24/// Owns a snapshot of a config variable. You may use operator* or operator->
25/// to access the config variable.
26template <typename VariableType>
27class VariableSnapshotPtr final {
28public:
29 VariableSnapshotPtr(VariableSnapshotPtr&&) = delete;
30 VariableSnapshotPtr& operator=(VariableSnapshotPtr&&) = delete;
31
32 const VariableType& operator*() const& USERVER_IMPL_LIFETIME_BOUND { return *variable_; }
33 const VariableType& operator*() && { ReportMisuse(); }
34
35 const VariableType* operator->() const& USERVER_IMPL_LIFETIME_BOUND { return variable_; }
36 const VariableType* operator->() && { ReportMisuse(); }
37
38private:
39 [[noreturn]] static void ReportMisuse() {
40 static_assert(!sizeof(VariableType), "keep the pointer before using, please");
41 }
42
43 explicit VariableSnapshotPtr(Snapshot&& snapshot, const Key<VariableType>& key)
44 : snapshot_(std::move(snapshot)),
45 variable_(&snapshot_[key])
46 {}
47
48 // for the constructor
49 friend class Source;
50
51 Snapshot snapshot_;
52 const VariableType* variable_;
53};
54
55/// @brief Helper class for subscribing to dynamic-config updates with a custom
56/// callback.
57///
58/// Stores information about the last update that occurred.
59///
60/// @param previous `dynamic_config::Snapshot` of the previous config or
61/// `std::nullopt` if this update event is the first for the subscriber.
62struct Diff final {
63 std::optional<Snapshot> previous;
64 Snapshot current;
65
66 template <typename... Keys>
67 bool HasConfigsChanged(const Keys&... keys) const {
68 if (!previous) {
69 return true;
70 }
71
72 UASSERT(!current.GetData().IsEmpty());
73 UASSERT(!previous->GetData().IsEmpty());
74
75 const bool is_equal = (true && ... && ((*previous)[keys] == current[keys]));
76 return !is_equal;
77 }
78};
79
80/// @ingroup userver_clients
81///
82/// @brief A client for easy dynamic config fetching in components.
83///
84/// After construction, dynamic_config::Source
85/// can be copied around and passed to clients or child helper classes.
86///
87/// Usually retrieved from components::DynamicConfig component.
88///
89/// Typical usage:
90/// @snippet core/src/components/component_sample_test.cpp Sample user component runtime config source
91class Source final {
92public:
93 using SnapshotEventSource = concurrent::AsyncEventSource<const Snapshot&>;
94 using DiffEventSource = concurrent::AsyncEventSource<const Diff&>;
95
96 /// For internal use only. Obtain using components::DynamicConfig or
97 /// dynamic_config::StorageMock instead.
98 explicit Source(impl::StorageData& storage);
99
100 // trivially copyable
101 Source(const Source&) = default;
102 Source(Source&&) = default;
103 Source& operator=(const Source&) = default;
104 Source& operator=(Source&&) = default;
105
106 Snapshot GetSnapshot() const;
107
108 template <typename VariableType>
109 VariableSnapshotPtr<VariableType> GetSnapshot(const Key<VariableType>& key) const {
110 return VariableSnapshotPtr{GetSnapshot(), key};
111 }
112
113 template <typename VariableType>
114 VariableType GetCopy(const Key<VariableType>& key) const {
115 const auto snapshot = GetSnapshot();
116 return snapshot[key];
117 }
118
119 /// Subscribes to dynamic-config updates using a member function. Also
120 /// immediately invokes the function with the current config snapshot (this
121 /// invocation will be executed synchronously).
122 ///
123 /// Further updates are delivered after @ref utils::ResourceScopeStorage::AfterConstruction, including those updates
124 /// that arrived before it. Unsubscribe runs in @ref utils::ResourceScopeStorage::BeforeDestruction.
125 ///
126 /// @note Callbacks occur in full accordance with
127 /// `components::DynamicConfigClientUpdater` options.
128 ///
129 /// @param scopes storage that owns the subscription lifetime.
130 /// See @ref resource_scopes_parameter "where to obtain scopes".
131 /// @param obj the subscriber, which is the owner of the listener method, and
132 /// is also used as the unique identifier of the subscription
133 /// @param name the name of the subscriber, for diagnostic purposes
134 /// @param func the listener method, named `OnConfigUpdate` by convention.
135 ///
136 /// @see based on concurrent::AsyncEventSource engine
137 template <typename Class>
139 utils::ResourceScopeStorage& scopes,
140 Class* obj,
141 std::string_view name,
142 void (Class::*func)(const dynamic_config::Snapshot& config)
143 ) {
144 DoUpdateAndListen(
145 scopes,
146 concurrent::FunctionId(obj),
147 name,
148 [obj, func](const dynamic_config::Snapshot& config) { (obj->*func)(config); }
149 );
150 }
151
152#ifndef ARCADIA_ROOT
153 /// @overload
154 /// @deprecated Use the overloads that take @ref utils::ResourceScopeStorage.
155 ///
156 /// Store the returned scope as a member and call `Unsubscribe` explicitly.
157 template <typename Class>
158 concurrent::AsyncEventSubscriberScope UpdateAndListen(
159 Class* obj,
160 std::string_view name,
161 void (Class::*func)(const dynamic_config::Snapshot& config)
162 ) {
163 return DoUpdateAndListen(
164 concurrent::FunctionId(obj),
165 name,
166 [obj, func](const dynamic_config::Snapshot& config) { (obj->*func)(config); }
167 );
168 }
169#endif
170
171 /// @brief Subscribes to dynamic-config updates with information about the
172 /// current and previous states.
173 ///
174 /// Subscribes to dynamic-config updates using a member function, named
175 /// `OnConfigUpdate` by convention. Also constructs `dynamic_config::Diff`
176 /// object using `std::nullopt` and current config snapshot, then immediately
177 /// invokes the function with it (this invocation will be executed
178 /// synchronously).
179 ///
180 /// Further updates are delivered after @ref utils::ResourceScopeStorage::AfterConstruction, including those updates
181 /// that arrived before it. Unsubscribe runs in @ref utils::ResourceScopeStorage::BeforeDestruction.
182 ///
183 /// @note Callbacks occur in full accordance with
184 /// `components::DynamicConfigClientUpdater` options.
185 ///
186 /// @warning In debug mode the last notification for any subscriber will be
187 /// called with `std::nullopt` and current config snapshot.
188 ///
189 /// Example usage:
190 /// @snippet core/src/dynamic_config/config_test.cpp Custom subscription for dynamic config update
191 ///
192 /// @param scopes storage that owns the subscription lifetime.
193 /// See @ref resource_scopes_parameter "where to obtain scopes".
194 /// @param obj the subscriber, which is the owner of the listener method, and
195 /// is also used as the unique identifier of the subscription
196 /// @param name the name of the subscriber, for diagnostic purposes
197 /// @param func the listener method, named `OnConfigUpdate` by convention.
198 ///
199 /// @see based on concurrent::AsyncEventSource engine
200 ///
201 /// @see dynamic_config::Diff
202 template <typename Class>
204 utils::ResourceScopeStorage& scopes,
205 Class* obj,
206 std::string_view name,
207 void (Class::*func)(const dynamic_config::Diff& diff)
208 ) {
209 DoUpdateAndListen(scopes, concurrent::FunctionId(obj), name, [obj, func](const dynamic_config::Diff& diff) {
210 (obj->*func)(diff);
211 });
212 }
213
214#ifndef ARCADIA_ROOT
215 /// @overload
216 /// @deprecated Use the overloads that take @ref utils::ResourceScopeStorage.
217 ///
218 /// Store the returned scope as a member and call `Unsubscribe` explicitly.
219 template <typename Class>
220 concurrent::AsyncEventSubscriberScope UpdateAndListen(
221 Class* obj,
222 std::string_view name,
223 void (Class::*func)(const dynamic_config::Diff& diff)
224 ) {
225 return DoUpdateAndListen(concurrent::FunctionId(obj), name, [obj, func](const dynamic_config::Diff& diff) {
226 (obj->*func)(diff);
227 });
228 }
229#endif
230
231 /// @brief Subscribes to updates of a subset of all configs.
232 ///
233 /// Subscribes to dynamic-config updates using a member function, named
234 /// `OnConfigUpdate` by convention. The function will be invoked if at least
235 /// one of the configs has been changed since the previous invocation. So at
236 /// the first time immediately invokes the function with the current config
237 /// snapshot (this invocation will be executed synchronously).
238 ///
239 /// Further updates are delivered after @ref utils::ResourceScopeStorage::AfterConstruction, including those updates
240 /// that arrived before it. Unsubscribe runs in @ref utils::ResourceScopeStorage::BeforeDestruction.
241 ///
242 /// @note Callbacks occur only if one of the passed config is changed. This is
243 /// true under any components::DynamicConfigClientUpdater options.
244 ///
245 /// @warning To use this function, configs must have the `operator==`.
246 ///
247 /// @param scopes storage that owns the subscription lifetime.
248 /// See @ref resource_scopes_parameter "where to obtain scopes".
249 /// @param obj the subscriber, which is the owner of the listener method, and
250 /// is also used as the unique identifier of the subscription
251 /// @param name the name of the subscriber, for diagnostic purposes
252 /// @param func the listener method, named `OnConfigUpdate` by convention.
253 /// @param keys config objects, specializations of `dynamic_config::Key`.
254 ///
255 /// @see based on concurrent::AsyncEventSource engine
256 template <typename Class, typename... Keys>
258 utils::ResourceScopeStorage& scopes,
259 Class* obj,
260 std::string_view name,
261 void (Class::*func)(const dynamic_config::Snapshot& config),
262 const Keys&... keys
263 ) {
264 auto wrapper = [obj, func, &keys...](const Diff& diff) {
265 if (!diff.HasConfigsChanged(keys...)) {
266 return;
267 }
268 (obj->*func)(diff.current);
269 };
270 DoUpdateAndListen(scopes, concurrent::FunctionId(obj), name, std::move(wrapper));
271 }
272
273#ifndef ARCADIA_ROOT
274 /// @overload
275 /// @deprecated Use the overloads that take @ref utils::ResourceScopeStorage.
276 ///
277 /// Store the returned scope as a member and call `Unsubscribe` explicitly.
278 template <typename Class, typename... Keys>
279 concurrent::AsyncEventSubscriberScope UpdateAndListen(
280 Class* obj,
281 std::string_view name,
282 void (Class::*func)(const dynamic_config::Snapshot& config),
283 const Keys&... keys
284 ) {
285 auto wrapper = [obj, func, &keys...](const Diff& diff) {
286 if (!diff.HasConfigsChanged(keys...)) {
287 return;
288 }
289 (obj->*func)(diff.current);
290 };
291 return DoUpdateAndListen(concurrent::FunctionId(obj), name, std::move(wrapper));
292 }
293#endif
294
295 SnapshotEventSource& GetEventChannel();
296
297private:
298#ifndef ARCADIA_ROOT
299 concurrent::AsyncEventSubscriberScope DoUpdateAndListen(
300 concurrent::FunctionId id,
301 std::string_view name,
302 SnapshotEventSource::Function&& func
303 );
304
305 concurrent::AsyncEventSubscriberScope DoUpdateAndListen(
306 concurrent::FunctionId id,
307 std::string_view name,
308 DiffEventSource::Function&& func
309 );
310#endif
311
312 void DoUpdateAndListen(
313 utils::ResourceScopeStorage& scopes,
314 concurrent::FunctionId id,
315 std::string_view name,
316 SnapshotEventSource::Function&& func
317 );
318
319 void DoUpdateAndListen(
320 utils::ResourceScopeStorage& scopes,
321 concurrent::FunctionId id,
322 std::string_view name,
323 DiffEventSource::Function&& func
324 );
325
326 impl::StorageData* storage_;
327};
328
329/// @brief Allows to subscribe to `components::DynamicConfig` updates without waiting for
330/// the first update to complete. Primarily intended for internal use.
331class NoblockSubscriber final {
332public:
333 explicit NoblockSubscriber(components::DynamicConfig& config_component) noexcept;
334
335 NoblockSubscriber(NoblockSubscriber&&) = delete;
336 NoblockSubscriber& operator=(NoblockSubscriber&&) = delete;
337
338 /// @brief Subscribes to dynamic-config updates without waiting for the first update.
339 ///
340 /// If a config snapshot is already loaded when the scope is entered, constructs
341 /// @ref dynamic_config::Diff from `std::nullopt` and the current snapshot and
342 /// invokes the listener. Otherwise only subscribes; the listener is first invoked
343 /// when a snapshot arrives.
344 ///
345 /// Further updates are delivered after @ref utils::ResourceScopeStorage::AfterConstruction.
346 /// Unsubscribe runs in @ref utils::ResourceScopeStorage::BeforeDestruction.
347 ///
348 /// @note Callbacks occur in full accordance with
349 /// @ref components::DynamicConfigClientUpdater options.
350 ///
351 /// @warning In debug mode the last notification for any subscriber will be
352 /// called with `std::nullopt` and current config snapshot.
353 ///
354 /// @param scopes storage that owns the subscription lifetime.
355 /// See @ref resource_scopes_parameter "where to obtain scopes".
356 /// @param obj the subscriber, which is the owner of the listener method, and
357 /// is also used as the unique identifier of the subscription
358 /// @param name the name of the subscriber, for diagnostic purposes
359 /// @param func the listener method, named `OnConfigUpdate` by convention.
360 ///
361 /// @see based on @ref concurrent::AsyncEventSource engine
362 ///
363 /// @see dynamic_config::Diff
364 template <typename Class>
366 utils::ResourceScopeStorage& scopes,
367 Class* obj,
368 std::string_view name,
369 void (Class::*func)(const dynamic_config::Diff& diff)
370 ) {
371 DoUpdateIfHasConfigAndListen(
372 scopes,
373 concurrent::FunctionId(obj),
374 name,
375 [obj, func](const dynamic_config::Diff& diff) { (obj->*func)(diff); }
376 );
377 }
378
379private:
380 void DoUpdateIfHasConfigAndListen(
381 utils::ResourceScopeStorage& scopes,
382 concurrent::FunctionId id,
383 std::string_view name,
384 concurrent::AsyncEventSource<const dynamic_config::Diff&>::Function&& func
385 );
386
387 components::DynamicConfig& config_component_;
388};
389
390} // namespace dynamic_config
391
392USERVER_NAMESPACE_END