userver: userver/concurrent/async_event_channel.hpp Source File
Loading...
Searching...
No Matches
async_event_channel.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/concurrent/async_event_channel.hpp
4/// @brief @copybrief concurrent::AsyncEventChannel
5
6#include <functional>
7#include <string>
8#include <string_view>
9#include <typeindex>
10#include <unordered_map>
11#include <utility>
12#include <vector>
13
14#include <userver/concurrent/async_event_source.hpp>
15#include <userver/concurrent/variable.hpp>
16#include <userver/engine/semaphore.hpp>
17#include <userver/engine/shared_mutex.hpp>
18#include <userver/engine/task/cancel.hpp>
19#include <userver/engine/task/task_with_result.hpp>
20#include <userver/utils/assert.hpp>
21#include <userver/utils/async.hpp>
22
23USERVER_NAMESPACE_BEGIN
24
25namespace concurrent {
26
27namespace impl {
28
29void WaitForTask(std::string_view name, engine::TaskWithResult<void>& task);
30
31[[noreturn]] void ReportAlreadySubscribed(std::string_view channel_name, std::string_view listener_name);
32
33void ReportNotSubscribed(std::string_view channel_name) noexcept;
34
35void ReportUnsubscribingAutomatically(std::string_view channel_name, std::string_view listener_name) noexcept;
36
37void ReportErrorWhileUnsubscribing(
38 std::string_view channel_name,
39 std::string_view listener_name,
40 std::string_view error
41) noexcept;
42
43std::string MakeAsyncChannelName(std::string_view base, std::string_view name);
44
45inline constexpr bool kCheckSubscriptionUB = utils::impl::kEnableAssert;
46
47// During the `AsyncEventSubscriberScope::Unsubscribe` call or destruction of
48// `AsyncEventSubscriberScope`, all variables used by callback must be valid
49// (must not be destroyed). A common cause of crashes in this place: there is no
50// manual call to `Unsubscribe`. In this case check the declaration order of the
51// struct fields.
52template <typename Func>
53void CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing(
54 std::function<void(const Func&)>& on_listener_removal,
55 const Func& listener_func,
56 std::string_view channel_name,
57 std::string_view listener_name
58) noexcept {
59 if (!on_listener_removal) {
60 return;
61 }
62 try {
63 on_listener_removal(listener_func);
64 } catch (const std::exception& e) {
65 ReportErrorWhileUnsubscribing(channel_name, listener_name, e.what());
66 }
67}
68
69} // namespace impl
70
71/// @ingroup userver_concurrency
72///
73/// AsyncEventChannel is an in-process pub-sub with strict FIFO serialization,
74/// i.e. only after the event was processed a new event may appear for
75/// processing, same listener is never called concurrently.
76///
77/// Example usage:
78/// @snippet concurrent/async_event_channel_test.cpp AsyncEventChannel sample
79template <typename... Args>
80class AsyncEventChannel : public AsyncEventSource<Args...> {
81public:
82 using Function = typename AsyncEventSource<Args...>::Function;
83 using OnRemoveCallback = std::function<void(const Function&)>;
84
85 /// @brief The primary constructor
86 /// @param name used for diagnostic purposes and is also accessible with Name
87 explicit AsyncEventChannel(std::string_view name)
88 : name_(name),
89 data_(ListenersData{{}, {}})
90 {}
91
92 /// @brief The constructor with `AsyncEventSubscriberScope` usage checking.
93 ///
94 /// The constructor with a callback that is called on listener removal. The
95 /// callback takes a reference to `Function` as input. This is useful for
96 /// checking the lifetime of data captured by the listener update function.
97 ///
98 /// @note Works only in debug mode.
99 ///
100 /// @warning Data captured by `on_listener_removal` function must be valid
101 /// until the `AsyncEventChannel` object is completely destroyed.
102 ///
103 /// Example usage:
104 /// @snippet concurrent/async_event_channel_test.cpp OnListenerRemoval sample
105 ///
106 /// @param name used for diagnostic purposes and is also accessible with Name
107 /// @param on_listener_removal the callback used for check
108 ///
109 /// @see impl::CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing
110 AsyncEventChannel(std::string_view name, OnRemoveCallback on_listener_removal)
111 : name_(name),
112 data_(ListenersData{{}, std::move(on_listener_removal)})
113 {}
114
115 /// @brief For use in `UpdateAndListen` of specific event channels
116 ///
117 /// Atomically calls `updater`, which should invoke `func` with the previously
118 /// sent event, and subscribes to new events as if using AddListener.
119 ///
120 /// @param id the subscriber class instance, see also a simpler `DoUpdateAndListen` overload below
121 /// @param name the name of the subscriber
122 /// @param func the callback that is called on each update
123 /// @param updater the initial `() -> void` callback that should call `func` with the current value
124 ///
125 /// @see AsyncEventSource::AddListener
126 template <typename UpdaterFunc>
127 AsyncEventSubscriberScope DoUpdateAndListen(
128 FunctionId id,
129 std::string_view name,
130 Function&& func,
131 UpdaterFunc&& updater
132 ) {
133 const std::shared_lock lock(event_mutex_);
134 std::forward<UpdaterFunc>(updater)();
135 return DoAddListener(id, name, std::move(func));
136 }
137
138 /// @overload
139 template <typename Class, typename UpdaterFunc>
140 AsyncEventSubscriberScope DoUpdateAndListen(
141 Class* obj,
142 std::string_view name,
143 void (Class::*func)(Args...),
144 UpdaterFunc&& updater
145 ) {
146 return DoUpdateAndListen(
147 FunctionId(obj),
148 name,
149 [obj, func](Args... args) { (obj->*func)(args...); },
150 std::forward<UpdaterFunc>(updater)
151 );
152 }
153
154 /// Send the next event and wait until all the listeners process it.
155 ///
156 /// Strict FIFO serialization is guaranteed, i.e. only after this event is
157 /// processed a new event may be delivered for the subscribers, same
158 /// listener/subscriber is never called concurrently.
159 void SendEvent(Args... args) const {
160 struct Task {
161 std::shared_ptr<const Listener> listener;
162 engine::TaskWithResult<void> task;
163 };
164 std::vector<Task> tasks;
165
166 // Try to obtain unique lock for event_mutex_ to serialize
167 // calls to SendEvent()
168 event_mutex_.lock();
169
170 // Now downgrade the lock to shared to allow new subscriptions
171 event_mutex_.unlock_and_lock_shared();
172
173 // And ensure the lock releases in case of an exception
174 std::shared_lock<engine::SharedMutex> tmp_lock{event_mutex_, std::adopt_lock};
175
176 // Now we want to create N subtasks for callbacks,
177 // which must hold event_mutex_'s std::shared_lock.
178 // A naive implementation would create std::shared_lock{event_mutex_} for each subtask,
179 // however, it might deadlock if any parallel SendEvent() is called and is blocked on
180 // event_mutex_.lock(). It happens due to strict prioritization of writers above readers
181 // in SharedMutex: if there is any pending writer, nobody may lock the mutex for read.
182 {
183 auto data = data_.Lock();
184 auto& listeners = data->listeners;
185 tasks.reserve(listeners.size());
186
187 for (const auto& [_, listener] : listeners) {
188 tasks.push_back(Task{
189 listener, // an intentional copy
190 utils::Async(
191 listener->task_name,
192 [&, &callback = listener->callback, sema_lock = std::shared_lock(listener->sema)] {
193 callback(args...);
194 }
195 ),
196 });
197 }
198 }
199 // Unlock data_ here because callbacks may subscribe to this
200
201 for (auto& task : tasks) {
202 impl::WaitForTask(task.listener->name, task.task);
203 }
204 }
205
206 /// @returns the name of this event channel
207 const std::string& Name() const noexcept { return name_; }
208
209private:
210 struct Listener final {
211 // 'sema' with data_.Lock() are used to synchronize removal 'Listener' from ListenersData::listeners
212 mutable engine::Semaphore sema;
213
214 std::string name;
215 Function callback;
216 std::string task_name;
217
218 Listener(std::string name, Function callback, std::string task_name)
219 : sema(1),
220 name(std::move(name)),
221 callback(std::move(callback)),
222 task_name(std::move(task_name))
223 {}
224 };
225
226 struct ListenersData final {
227 std::unordered_map<FunctionId, std::shared_ptr<const Listener>, FunctionId::Hash> listeners;
228 OnRemoveCallback on_listener_removal;
229 };
230
231 void RemoveListener(FunctionId id, UnsubscribingKind kind) noexcept final {
232 const engine::TaskCancellationBlocker blocker;
233 const std::shared_lock lock(event_mutex_);
234 std::shared_ptr<const Listener> listener;
235 OnRemoveCallback on_listener_removal;
236
237 {
238 auto data = data_.Lock();
239 auto& listeners = data->listeners;
240 const auto iter = listeners.find(id);
241
242 if (iter == listeners.end()) {
243 impl::ReportNotSubscribed(Name());
244 return;
245 }
246
247 listener = iter->second;
248
249 on_listener_removal = data->on_listener_removal;
250
251 listeners.erase(iter);
252
253 // Lock and unlock sema under data_.Lock(),
254 // now we're sure that SendEvent() will not trigger listener->callback()
255 (void)std::shared_lock(listener->sema);
256 }
257 // Unlock data_ here to be able to (un)subscribe to *this in listener->callback (in debug)
258 // without deadlock
259
260 if (kind == UnsubscribingKind::kAutomatic) {
261 if (!on_listener_removal) {
262 impl::ReportUnsubscribingAutomatically(name_, listener->name);
263 }
264
265 if constexpr (impl::kCheckSubscriptionUB) {
266 // Fake listener call to check
267 impl::CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing(
268 on_listener_removal,
269 listener->callback,
270 name_,
271 listener->name
272 );
273 }
274 }
275 }
276
277 AsyncEventSubscriberScope DoAddListener(FunctionId id, std::string_view name, Function&& func) final {
278 UASSERT(id);
279
280 auto data = data_.Lock();
281 auto& listeners = data->listeners;
282 auto task_name = impl::MakeAsyncChannelName(name_, name);
283 const auto [iterator, success] = listeners.emplace(
284 id,
285 std::make_shared<const Listener>(std::string{name}, std::move(func), std::move(task_name))
286 );
287 if (!success) {
288 impl::ReportAlreadySubscribed(Name(), name);
289 }
290 return AsyncEventSubscriberScope(utils::impl::InternalTag{}, *this, id);
291 }
292
293 const std::string name_;
294 concurrent::Variable<ListenersData> data_;
295
296 // event_mutex_ is required only for event serialization,
297 // it doesn't protect any data. The mutex is unique locked
298 // for new event publishing, and is shared locked for calling callbacks.
299 // If any callback is working, no new event publishing is possible.
300 // It *is* possible to re-subscribe on async channel while another callback
301 // operates.
302 mutable engine::SharedMutex event_mutex_;
303};
304
305} // namespace concurrent
306
307USERVER_NAMESPACE_END