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 <cstdint>
7#include <functional>
8#include <memory>
9#include <mutex>
10#include <shared_mutex>
11#include <string>
12#include <string_view>
13#include <typeindex>
14#include <unordered_map>
15#include <utility>
16#include <vector>
17
18#include <userver/concurrent/async_event_source.hpp>
19#include <userver/concurrent/variable.hpp>
20#include <userver/engine/semaphore.hpp>
21#include <userver/engine/shared_mutex.hpp>
22#include <userver/engine/task/cancel.hpp>
23#include <userver/engine/task/task_with_result.hpp>
24#include <userver/utils/assert.hpp>
25#include <userver/utils/async.hpp>
26#include <userver/utils/resource_scopes.hpp>
27
28USERVER_NAMESPACE_BEGIN
29
30namespace concurrent {
31
32namespace impl {
33
34struct AsyncEventChannelTestAccessor;
35
36std::shared_lock<engine::SharedMutex> DowngradeLock(std::unique_lock<engine::SharedMutex> lock);
37
38void WaitForTask(std::string_view name, engine::TaskWithResult<void>& task);
39
40[[noreturn]] void ReportAlreadySubscribed(std::string_view channel_name, std::string_view listener_name);
41
42void ReportNotSubscribed(std::string_view channel_name) noexcept;
43
44void ReportErrorWhileUnsubscribing(
45 std::string_view channel_name,
46 std::string_view listener_name,
47 std::string_view error
48) noexcept;
49
50std::string MakeAsyncChannelName(std::string_view base, std::string_view name);
51
52inline constexpr bool kCheckSubscriptionUB = utils::impl::kEnableAssert;
53
54// During `AsyncEventSubscriberScope::Unsubscribe` or automatic teardown
55// (scope destructor / ResourceScopeStorage::BeforeDestruction), all variables
56// used by the callback must still be valid. A common cause of crashes here:
57// the subscription is removed after the captured data is destroyed.
58template <typename Func>
59void CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing(
60 std::function<void(const Func&)>& on_listener_removal,
61 const Func& listener_func,
62 std::string_view channel_name,
63 std::string_view listener_name
64) noexcept {
65 if (!on_listener_removal) {
66 return;
67 }
68 try {
69 on_listener_removal(listener_func);
70 } catch (const std::exception& e) {
71 ReportErrorWhileUnsubscribing(channel_name, listener_name, e.what());
72 }
73}
74
75} // namespace impl
76
77/// @ingroup userver_concurrency
78///
79/// AsyncEventChannel is an in-process pub-sub with strict FIFO serialization,
80/// i.e. only after the event was processed a new event may appear for
81/// processing, same listener is never called concurrently.
82///
83/// Example usage:
84/// @snippet core/src/concurrent/async_event_channel_test.cpp AsyncEventChannel sample
85template <typename... Args>
86class AsyncEventChannel : public AsyncEventSource<Args...> {
87public:
88 using Function = typename AsyncEventSource<Args...>::Function;
89 using OnRemoveCallback = std::function<void(const Function&)>;
90
91 /// @brief The primary constructor
92 /// @param name used for diagnostic purposes and is also accessible with Name
93 explicit AsyncEventChannel(std::string_view name)
94 : name_(name),
95 data_(ListenersData{{}, {}})
96 {}
97
98 /// @brief The constructor with `AsyncEventSubscriberScope` usage checking.
99 ///
100 /// The constructor with a callback that is called on listener removal,
101 /// both on `Unsubscribe` and on automatic teardown. The callback takes a
102 /// reference to `Function` as input. This is useful for checking the lifetime
103 /// of data captured by the listener update function.
104 ///
105 /// @note Works only in debug mode.
106 ///
107 /// @warning Data captured by `on_listener_removal` function must be valid
108 /// until the `AsyncEventChannel` object is completely destroyed.
109 ///
110 /// Example usage:
111 /// @snippet core/src/concurrent/async_event_channel_test.cpp OnListenerRemoval sample
112 ///
113 /// @param name used for diagnostic purposes and is also accessible with Name
114 /// @param on_listener_removal the callback used for check
115 ///
116 /// @see impl::CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing
117 AsyncEventChannel(std::string_view name, OnRemoveCallback on_listener_removal)
118 : name_(name),
119 data_(ListenersData{{}, std::move(on_listener_removal)})
120 {}
121
122#ifndef ARCADIA_ROOT
123 /// @brief For use in `UpdateAndListen` of specific event channels
124 ///
125 /// Atomically calls `updater`, which should invoke `func` with the previously
126 /// sent event, and subscribes to new events as if using AddListener.
127 ///
128 /// @param id the subscriber class instance, see also a simpler `DoUpdateAndListen` overload below
129 /// @param name the name of the subscriber
130 /// @param func the callback that is called on each update
131 /// @param updater the initial `() -> void` callback that should call `func` with the current value
132 ///
133 /// @see AsyncEventSource::AddListener
134 template <typename UpdaterFunc>
135 AsyncEventSubscriberScope DoUpdateAndListen(
136 FunctionId id,
137 std::string_view name,
138 Function&& func,
139 UpdaterFunc&& updater
140 ) {
141 const std::shared_lock lock(event_mutex_);
142 std::forward<UpdaterFunc>(updater)();
143 return DoAddListener(id, name, std::move(func));
144 }
145
146 /// @overload
147 template <typename Class, typename UpdaterFunc>
148 AsyncEventSubscriberScope DoUpdateAndListen(
149 Class* obj,
150 std::string_view name,
151 void (Class::*func)(Args...),
152 UpdaterFunc&& updater
153 ) {
154 return DoUpdateAndListen(
155 FunctionId(obj),
156 name,
157 [obj, func](Args... args) { (obj->*func)(args...); },
158 std::forward<UpdaterFunc>(updater)
159 );
160 }
161#endif
162
163 /// @brief Like @ref DoUpdateAndListen, but binds the subscription to @a scopes.
164 ///
165 /// Synchronously calls @a updater and records the channel's event generation. When the scope is entered,
166 /// @a updater is called again if an event was sent during construction, then @a func is subscribed atomically
167 /// with that check. Unsubscribes on scope exit.
168 ///
169 /// @warning @a updater is not only invoked inline. It is stored and may run again after this call returns,
170 /// when the scope is entered. Do not capture locals by reference: copy the pointers and values the updater
171 /// needs (for example @c obj and @c func) and capture @c this explicitly.
172 ///
173 /// @param scopes storage that owns the subscription lifetime.
174 /// See @ref resource_scopes_parameter "where to obtain scopes".
175 template <typename UpdaterFunc>
177 utils::ResourceScopeStorage& scopes,
178 FunctionId id,
179 std::string_view name,
180 Function&& func,
181 UpdaterFunc&& updater
182 ) {
183 const auto initial_generation = [this, &updater] {
184 const std::shared_lock lock(event_mutex_);
185 updater();
186 return event_generation_;
187 }();
188
189 // The first callback runs synchronously in the constructor, so the subscription
190 // lifetime must be longer than that of other scope types.
191 constexpr utils::ResourceScopeStorage::Priority kPriority{-1};
192 scopes.Register(
193 utils::impl::InternalTag{},
194 kPriority,
195 [this,
196 id,
197 name = std::string{name},
198 initial_generation,
199 func = std::move(func),
200 updater = std::forward<UpdaterFunc>(updater)]() mutable {
201 const std::shared_lock lock(event_mutex_);
202 if (event_generation_ != initial_generation) {
203 updater();
204 }
205 return DoAddListener(id, name, std::move(func));
206 }
207 );
208 }
209
210 /// @overload
211 /// @param scopes storage that owns the subscription lifetime.
212 /// See @ref resource_scopes_parameter "where to obtain scopes".
213 template <typename Class, typename UpdaterFunc>
215 utils::ResourceScopeStorage& scopes,
216 Class* obj,
217 std::string_view name,
218 void (Class::*func)(Args...),
219 UpdaterFunc&& updater
220 ) {
221 DoUpdateAndListen(
222 scopes,
223 FunctionId(obj),
224 name,
225 [obj, func](Args... args) { (obj->*func)(args...); },
226 std::forward<UpdaterFunc>(updater)
227 );
228 }
229
230#ifndef ARCADIA_ROOT
231
232 /// @deprecated Use @ref concurrent::AsyncEventChannel::DoUpdateAndListen instead.
233 template <typename UpdaterFunc>
235 utils::ResourceScopeStorage& scopes,
236 FunctionId id,
237 std::string_view name,
238 Function&& func,
239 UpdaterFunc&& updater
240 ) {
241 DoUpdateAndListen(scopes, id, name, std::move(func), std::forward<UpdaterFunc>(updater));
242 }
243
244 /// @deprecated Use @ref concurrent::AsyncEventChannel::DoUpdateAndListen instead.
245 template <typename Class, typename UpdaterFunc>
247 utils::ResourceScopeStorage& scopes,
248 Class* obj,
249 std::string_view name,
250 void (Class::*func)(Args...),
251 UpdaterFunc&& updater
252 ) {
253 DoUpdateAndListen(scopes, obj, name, func, std::forward<UpdaterFunc>(updater));
254 }
255
256#endif
257
258 /// Send the next event and wait until all the listeners process it.
259 ///
260 /// Strict FIFO serialization is guaranteed, i.e. only after this event is
261 /// processed a new event may be delivered for the subscribers, same
262 /// listener/subscriber is never called concurrently.
263 void SendEvent(Args... args) const {
264 struct Task {
265 std::shared_ptr<const Listener> listener;
266 engine::TaskWithResult<void> task;
267 };
268 std::vector<Task> tasks;
269
270 std::shared_lock<engine::SharedMutex> tmp_lock;
271 {
272 // Try to obtain unique lock for event_mutex_ to serialize
273 // calls to SendEvent()
274 std::unique_lock lock(event_mutex_);
275 auto data = data_.Lock();
276 ++event_generation_;
277
278 tmp_lock = impl::DowngradeLock(std::move(lock));
279
280 // Now we want to create N subtasks for callbacks,
281 // which must hold event_mutex_'s std::shared_lock.
282 // A naive implementation would create std::shared_lock{event_mutex_} for each subtask,
283 // however, it might deadlock if any parallel SendEvent() is called and is blocked on
284 // event_mutex_.lock(). It happens due to strict prioritization of writers above readers
285 // in SharedMutex: if there is any pending writer, nobody may lock the mutex for read.
286 auto& listeners = data->listeners;
287 tasks.reserve(listeners.size());
288
289 for (const auto& [_, listener] : listeners) {
290 tasks.push_back(Task{
291 listener, // an intentional copy
292 utils::Async(
293 listener->task_name,
294 [&, &callback = listener->callback, sema_lock = std::shared_lock(listener->sema)] {
295 callback(args...);
296 }
297 ),
298 });
299 }
300 }
301 // Unlock data_ here because callbacks may subscribe to this
302
303 for (auto& task : tasks) {
304 impl::WaitForTask(task.listener->name, task.task);
305 }
306 }
307
308 /// @returns the name of this event channel
309 const std::string& Name() const noexcept { return name_; }
310
311private:
312 friend struct impl::AsyncEventChannelTestAccessor;
313
314 struct Listener final {
315 // 'sema' with data_.Lock() are used to synchronize removal 'Listener' from ListenersData::listeners
316 mutable engine::Semaphore sema;
317
318 std::string name;
319 Function callback;
320 std::string task_name;
321
322 Listener(std::string name, Function callback, std::string task_name)
323 : sema(1),
324 name(std::move(name)),
325 callback(std::move(callback)),
326 task_name(std::move(task_name))
327 {}
328 };
329
330 struct ListenersData final {
331 std::unordered_map<FunctionId, std::shared_ptr<const Listener>, FunctionId::Hash> listeners;
332 OnRemoveCallback on_listener_removal;
333 };
334
335 void RemoveListener(FunctionId id, [[maybe_unused]] UnsubscribingKind kind) noexcept final {
336 const engine::TaskCancellationBlocker blocker;
337 const std::shared_lock lock(event_mutex_);
338 std::shared_ptr<const Listener> listener;
339 OnRemoveCallback on_listener_removal;
340
341 {
342 auto data = data_.Lock();
343 auto& listeners = data->listeners;
344 const auto iter = listeners.find(id);
345
346 if (iter == listeners.end()) {
347 impl::ReportNotSubscribed(Name());
348 return;
349 }
350
351 listener = iter->second;
352
353 on_listener_removal = data->on_listener_removal;
354
355 listeners.erase(iter);
356
357 // Lock and unlock sema under data_.Lock(),
358 // now we're sure that SendEvent() will not trigger listener->callback()
359 (void)std::shared_lock(listener->sema);
360 }
361 // Unlock data_ here to be able to (un)subscribe to *this in listener->callback (in debug)
362 // without deadlock
363
364 if constexpr (impl::kCheckSubscriptionUB) {
365 // Fake listener call to check
366 impl::CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing(
367 on_listener_removal,
368 listener->callback,
369 name_,
370 listener->name
371 );
372 }
373 }
374
375 AsyncEventSubscriberScope DoAddListener(FunctionId id, std::string_view name, Function&& func) final {
376 UASSERT(id);
377
378 auto data = data_.Lock();
379 auto& listeners = data->listeners;
380 auto task_name = impl::MakeAsyncChannelName(name_, name);
381 const auto [iterator, success] = listeners.emplace(
382 id,
383 std::make_shared<const Listener>(std::string{name}, std::move(func), std::move(task_name))
384 );
385 if (!success) {
386 impl::ReportAlreadySubscribed(Name(), name);
387 }
388 return AsyncEventSubscriberScope(utils::impl::InternalTag{}, *this, id);
389 }
390
391 const std::string name_;
392 concurrent::Variable<ListenersData> data_;
393
394 // The mutex is unique locked
395 // for new event publishing, and is shared locked for calling callbacks.
396 // If any callback is working, no new event publishing is possible.
397 // It *is* possible to re-subscribe on async channel while another callback
398 // operates.
399 mutable engine::SharedMutex event_mutex_;
400 mutable std::uint64_t event_generation_{0};
401};
402
403} // namespace concurrent
404
405USERVER_NAMESPACE_END