userver: userver/concurrent/async_event_source.hpp Source File
Loading...
Searching...
No Matches
async_event_source.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/concurrent/async_event_source.hpp
4/// @brief @copybrief concurrent::AsyncEventSource
5
6#include <cstddef>
7#include <functional>
8#include <string>
9#include <string_view>
10#include <typeinfo>
11#include <utility>
12
13#include <userver/utils/impl/internal_tag.hpp>
14#include <userver/utils/resource_scopes.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace concurrent {
19
20class FunctionId;
21enum class UnsubscribingKind;
22
23template <typename... Args>
25
26namespace impl {
27
28class AsyncEventSourceBase {
29public:
30 virtual void RemoveListener(FunctionId, UnsubscribingKind) noexcept = 0;
31
32protected:
33 // disallow deletion via pointer to base
34 ~AsyncEventSourceBase();
35};
36
37} // namespace impl
38
39/// Uniquely identifies a subscription (usually the callback method owner) for
40/// AsyncEventSource
41class FunctionId final {
42public:
43 constexpr FunctionId() = default;
44
45 template <typename Class>
46 explicit FunctionId(Class* obj)
47 : FunctionId(obj, typeid(Class))
48 {}
49
50 explicit operator bool() const;
51
52 bool operator==(const FunctionId& other) const;
53
54 struct Hash final {
55 std::size_t operator()(FunctionId id) const noexcept;
56 };
57
58private:
59 FunctionId(void* ptr, const std::type_info& type);
60
61 void* ptr_{nullptr};
62 const std::type_info* type_{nullptr};
63};
64
65enum class UnsubscribingKind { kManual, kAutomatic };
66
67/// @brief Manages the subscription to events from an AsyncEventSource
68///
69/// Removes the associated listener automatically on destruction.
70///
71/// Store the Scope as a member and call `Unsubscribe` manually
72/// in the object's destructor, before anything that the callback needs
73/// is destroyed.
74class [[nodiscard]] AsyncEventSubscriberScope final {
75public:
76 AsyncEventSubscriberScope() = default;
77
78 AsyncEventSubscriberScope(AsyncEventSubscriberScope&& scope) noexcept;
79 AsyncEventSubscriberScope& operator=(AsyncEventSubscriberScope&& other) noexcept;
80 ~AsyncEventSubscriberScope();
81
82 /// Unsubscribes manually. The subscription should be cancelled before
83 /// anything that the callback needs is destroyed.
84 void Unsubscribe() noexcept;
85
86 /// @cond
87 // For internal use only.
88 template <typename... Args>
89 AsyncEventSubscriberScope(utils::impl::InternalTag, AsyncEventSource<Args...>& channel, FunctionId id)
90 : AsyncEventSubscriberScope(static_cast<impl::AsyncEventSourceBase&>(channel), id)
91 {}
92 /// @endcond
93
94private:
95 AsyncEventSubscriberScope(impl::AsyncEventSourceBase& channel, FunctionId id);
96
97 impl::AsyncEventSourceBase* channel_{nullptr};
98 FunctionId id_;
99};
100
101/// @ingroup userver_concurrency
102///
103/// @brief The read-only side of an event channel. Events are delivered to
104/// listeners in a strict FIFO order, i.e. only after the event was processed
105/// a new event may appear for processing, same listener is never called
106/// concurrently.
107template <typename... Args>
108class AsyncEventSource : public impl::AsyncEventSourceBase {
109public:
110 using Function = std::function<void(Args... args)>;
111
112 virtual ~AsyncEventSource() = default;
113
114 /// @brief Subscribes to updates from this event source
115 ///
116 /// The listener won't be called immediately.
117 ///
118 /// Example usage:
119 /// @snippet core/src/concurrent/async_event_channel_test.cpp AddListener sample
120 ///
121 /// Subscription starts after @ref utils::ResourceScopeStorage::AfterConstruction.
122 /// Events sent before that are not delivered to the listener.
123 /// Unsubscribe runs in @ref utils::ResourceScopeStorage::BeforeDestruction.
124 /// This event source must outlive the resource scopes.
125 ///
126 /// @param scopes storage that owns the subscription lifetime.
127 /// See @ref resource_scopes_parameter "where to obtain scopes".
128 /// @param obj the subscriber, which is the owner of the listener method, and
129 /// is also used as the unique identifier of the subscription for this
130 /// AsyncEventSource
131 /// @param name the name of the subscriber, for diagnostic purposes
132 /// @param func the listener method, usually called `On<DataName>Update`, e.g.
133 /// `OnConfigUpdate` or `OnCacheUpdate`
134 ///
135 /// ## Possible races when using AddListener
136 ///
137 /// Manually processing the current value and subscribing in separate steps introduces a race. The following
138 /// pseudocode assumes that `scopes` is already active:
139 ///
140 /// ```cpp
141 /// OnCacheUpdate(cache.Get());
142 /// source.AddListener(scopes, this, "cache-listener", &MyClass::OnCacheUpdate);
143 /// ```
144 /// An update between reading the cache and subscribing is missed. Reversing the order also introduces a race:
145 ///
146 /// ```cpp
147 /// source.AddListener(scopes, this, "cache-listener", &MyClass::OnCacheUpdate);
148 /// OnCacheUpdate(cache.Get());
149 /// ```
150 /// The event callback may run concurrently with the manual call, possibly processing the same cache value twice.
151 ///
152 /// To process the current value and then listen to updates, use `UpdateAndListen` on the concrete data source, e.g.
153 /// @ref components::CachingComponentBase::UpdateAndListen. If only @ref concurrent::AsyncEventChannel is available,
154 /// use @ref concurrent::AsyncEventChannel::DoUpdateAndListen.
155 template <class Class>
157 utils::ResourceScopeStorage& scopes,
158 Class* obj,
159 std::string_view name,
160 void (Class::*func)(Args...)
161 ) {
162 AddListener(scopes, FunctionId(obj), name, [obj, func](Args... args) { (obj->*func)(args...); });
163 }
164
165 /// @brief A type-erased version of @ref concurrent::AsyncEventSource::AddListener.
166 /// @param scopes storage that owns the subscription lifetime.
167 /// See @ref resource_scopes_parameter "where to obtain scopes".
168 /// @param id the unique identifier of the subscription
169 /// @param name the name of the subscriber, for diagnostic purposes
170 /// @param func the callback used for event notifications
171 void AddListener(utils::ResourceScopeStorage& scopes, FunctionId id, std::string_view name, Function&& func) {
172 scopes.Register([this, id, name = std::string{name}, func = std::move(func)]() mutable {
173 return DoAddListener(id, name, std::move(func));
174 });
175 }
176
177#ifndef ARCADIA_ROOT
178 /// @overload
179 /// @deprecated Use the overload that takes @ref utils::ResourceScopeStorage.
180 /// Store the returned scope as a member and call `Unsubscribe` explicitly.
181 template <class Class>
182 AsyncEventSubscriberScope AddListener(Class* obj, std::string_view name, void (Class::*func)(Args...)) {
183 return AddListener(FunctionId(obj), name, [obj, func](Args... args) { (obj->*func)(args...); });
184 }
185
186 /// @brief A type-erased version of @ref concurrent::AsyncEventSource::AddListener.
187 /// @deprecated Use the overload that takes @ref utils::ResourceScopeStorage.
188 ///
189 /// @param id the unique identifier of the subscription
190 /// @param name the name of the subscriber, for diagnostic purposes
191 /// @param func the callback used for event notifications
192 AsyncEventSubscriberScope AddListener(FunctionId id, std::string_view name, Function&& func) {
193 return DoAddListener(id, name, std::move(func));
194 }
195
196#endif
197
198 /// Used by AsyncEventSubscriberScope to cancel an event subscription
199 void RemoveListener(FunctionId, UnsubscribingKind) noexcept override = 0;
200
201protected:
202 virtual AsyncEventSubscriberScope DoAddListener(FunctionId id, std::string_view name, Function&& func) = 0;
203};
204
205} // namespace concurrent
206
207USERVER_NAMESPACE_END