userver: userver/concurrent/async_event_channel.hpp Source File
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
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/mutex.hpp>
17#include <userver/engine/task/cancel.hpp>
18#include <userver/engine/task/task_with_result.hpp>
19#include <userver/utils/assert.hpp>
20#include <userver/utils/async.hpp>
21
22USERVER_NAMESPACE_BEGIN
23
24namespace concurrent {
25
26namespace impl {
27
28void WaitForTask(std::string_view name, engine::TaskWithResult<void>& task);
29
30[[noreturn]] void ReportAlreadySubscribed(std::string_view channel_name, std::string_view listener_name);
31
32void ReportNotSubscribed(std::string_view channel_name) noexcept;
33
34void ReportUnsubscribingAutomatically(std::string_view channel_name, std::string_view listener_name) noexcept;
35
36void ReportErrorWhileUnsubscribing(
37 std::string_view channel_name,
38 std::string_view listener_name,
39 std::string_view error
40) noexcept;
41
42std::string MakeAsyncChannelName(std::string_view base, std::string_view name);
43
44inline constexpr bool kCheckSubscriptionUB = utils::impl::kEnableAssert;
45
46// During the `AsyncEventSubscriberScope::Unsubscribe` call or destruction of
47// `AsyncEventSubscriberScope`, all variables used by callback must be valid
48// (must not be destroyed). A common cause of crashes in this place: there is no
49// manual call to `Unsubscribe`. In this case check the declaration order of the
50// struct fields.
51template <typename Func>
52void CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing(
53 std::function<void(Func&)>& on_listener_removal,
54 Func& listener_func,
55 std::string_view channel_name,
56 std::string_view listener_name
57) noexcept {
58 if (!on_listener_removal) return;
59 try {
60 on_listener_removal(listener_func);
61 } catch (const std::exception& e) {
62 ReportErrorWhileUnsubscribing(channel_name, listener_name, e.what());
63 }
64}
65
66} // namespace impl
67
68/// @ingroup userver_concurrency
69///
70/// AsyncEventChannel is an in-process pub-sub with strict FIFO serialization,
71/// i.e. only after the event was processed a new event may appear for
72/// processing, same listener is never called concurrently.
73///
74/// Example usage:
75/// @snippet concurrent/async_event_channel_test.cpp AsyncEventChannel sample
76template <typename... Args>
77class AsyncEventChannel : public AsyncEventSource<Args...> {
78public:
79 using Function = typename AsyncEventSource<Args...>::Function;
80 using OnRemoveCallback = std::function<void(Function&)>;
81
82 /// @brief The primary constructor
83 /// @param name used for diagnostic purposes and is also accessible with Name
84 explicit AsyncEventChannel(std::string_view name) : name_(name), data_(ListenersData{{}, {}}) {}
85
86 /// @brief The constructor with `AsyncEventSubscriberScope` usage checking.
87 ///
88 /// The constructor with a callback that is called on listener removal. The
89 /// callback takes a reference to `Function` as input. This is useful for
90 /// checking the lifetime of data captured by the listener update function.
91 ///
92 /// @note Works only in debug mode.
93 ///
94 /// @warning Data captured by `on_listener_removal` function must be valid
95 /// until the `AsyncEventChannel` object is completely destroyed.
96 ///
97 /// Example usage:
98 /// @snippet concurrent/async_event_channel_test.cpp OnListenerRemoval sample
99 ///
100 /// @param name used for diagnostic purposes and is also accessible with Name
101 /// @param on_listener_removal the callback used for check
102 ///
103 /// @see impl::CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing
104 AsyncEventChannel(std::string_view name, OnRemoveCallback on_listener_removal)
105 : name_(name), data_(ListenersData{{}, std::move(on_listener_removal)}) {}
106
107 /// @brief For use in `UpdateAndListen` of specific event channels
108 ///
109 /// Atomically calls `updater`, which should invoke `func` with the previously
110 /// sent event, and subscribes to new events as if using AddListener.
111 ///
112 /// @param id the subscriber class instance, see also a simpler `DoUpdateAndListen` overload below
113 /// @param name the name of the subscriber
114 /// @param func the callback that is called on each update
115 /// @param updater the initial `() -> void` callback that should call `func` with the current value
116 ///
117 /// @see AsyncEventSource::AddListener
118 template <typename UpdaterFunc>
119 AsyncEventSubscriberScope
120 DoUpdateAndListen(FunctionId id, std::string_view name, Function&& func, UpdaterFunc&& updater) {
121 std::lock_guard lock(event_mutex_);
122 std::forward<UpdaterFunc>(updater)();
123 return DoAddListener(id, name, std::move(func));
124 }
125
126 /// @overload
127 template <typename Class, typename UpdaterFunc>
128 AsyncEventSubscriberScope
129 DoUpdateAndListen(Class* obj, std::string_view name, void (Class::*func)(Args...), UpdaterFunc&& updater) {
130 return DoUpdateAndListen(
131 FunctionId(obj),
132 name,
133 [obj, func](Args... args) { (obj->*func)(args...); },
134 std::forward<UpdaterFunc>(updater)
135 );
136 }
137
138 /// Send the next event and wait until all the listeners process it.
139 ///
140 /// Strict FIFO serialization is guaranteed, i.e. only after this event is
141 /// processed a new event may be delivered for the subscribers, same
142 /// listener/subscriber is never called concurrently.
143 void SendEvent(Args... args) const {
144 std::lock_guard lock(event_mutex_);
145 auto data = data_.Lock();
146 auto& listeners = data->listeners;
147
148 std::vector<engine::TaskWithResult<void>> tasks;
149 tasks.reserve(listeners.size());
150
151 for (const auto& [_, listener] : listeners) {
152 tasks.push_back(utils::Async(listener.task_name, [&, &callback = listener.callback] { callback(args...); })
153 );
154 }
155
156 std::size_t i = 0;
157 for (const auto& [_, listener] : listeners) {
158 impl::WaitForTask(listener.name, tasks[i++]);
159 }
160 }
161
162 /// @returns the name of this event channel
163 const std::string& Name() const noexcept { return name_; }
164
165private:
166 struct Listener final {
167 std::string name;
168 Function callback;
169 std::string task_name;
170 };
171
172 struct ListenersData final {
173 std::unordered_map<FunctionId, Listener, FunctionId::Hash> listeners;
174 OnRemoveCallback on_listener_removal;
175 };
176
177 void RemoveListener(FunctionId id, UnsubscribingKind kind) noexcept final {
178 engine::TaskCancellationBlocker blocker;
179 auto data = data_.Lock();
180 auto& listeners = data->listeners;
181 const auto iter = listeners.find(id);
182
183 if (iter == listeners.end()) {
184 impl::ReportNotSubscribed(Name());
185 return;
186 }
187
188 if (kind == UnsubscribingKind::kAutomatic) {
189 if (!data->on_listener_removal) {
190 impl::ReportUnsubscribingAutomatically(name_, iter->second.name);
191 }
192
193 if constexpr (impl::kCheckSubscriptionUB) {
194 // Fake listener call to check
195 impl::CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing(
196 data->on_listener_removal, iter->second.callback, name_, iter->second.name
197 );
198 }
199 }
200 listeners.erase(iter);
201 }
202
203 AsyncEventSubscriberScope DoAddListener(FunctionId id, std::string_view name, Function&& func) final {
204 auto data = data_.Lock();
205 auto& listeners = data->listeners;
206 auto task_name = impl::MakeAsyncChannelName(name_, name);
207 const auto [iterator, success] =
208 listeners.emplace(id, Listener{std::string{name}, std::move(func), std::move(task_name)});
209 if (!success) impl::ReportAlreadySubscribed(Name(), name);
210 return AsyncEventSubscriberScope(utils::impl::InternalTag{}, *this, id);
211 }
212
213 const std::string name_;
214 concurrent::Variable<ListenersData> data_;
215 mutable engine::Mutex event_mutex_;
216};
217
218} // namespace concurrent
219
220USERVER_NAMESPACE_END