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/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)
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 /// @see AsyncEventSource::AddListener
113 template <typename UpdaterFunc>
114 AsyncEventSubscriberScope
115 DoUpdateAndListen(FunctionId id, std::string_view name, Function&& func, UpdaterFunc&& updater) {
116 std::lock_guard lock(event_mutex_);
117 std::forward<UpdaterFunc>(updater)();
118 return DoAddListener(id, name, std::move(func));
119 }
120
121 /// @overload
122 template <typename Class, typename UpdaterFunc>
123 AsyncEventSubscriberScope
124 DoUpdateAndListen(Class* obj, std::string_view name, void (Class::*func)(Args...), UpdaterFunc&& updater) {
125 return DoUpdateAndListen(
126 FunctionId(obj),
127 name,
128 [obj, func](Args... args) { (obj->*func)(args...); },
129 std::forward<UpdaterFunc>(updater)
130 );
131 }
132
133 /// Send the next event and wait until all the listeners process it.
134 ///
135 /// Strict FIFO serialization is guaranteed, i.e. only after this event is
136 /// processed a new event may be delivered for the subscribers, same
137 /// listener/subscriber is never called concurrently.
138 void SendEvent(Args... args) const {
139 std::lock_guard lock(event_mutex_);
140 auto data = data_.Lock();
141 auto& listeners = data->listeners;
142
143 std::vector<engine::TaskWithResult<void>> tasks;
144 tasks.reserve(listeners.size());
145
146 for (const auto& [_, listener] : listeners) {
147 tasks.push_back(utils::Async(listener.task_name, [&, &callback = listener.callback] { callback(args...); })
148 );
149 }
150
151 std::size_t i = 0;
152 for (const auto& [_, listener] : listeners) {
153 impl::WaitForTask(listener.name, tasks[i++]);
154 }
155 }
156
157 /// @returns the name of this event channel
158 const std::string& Name() const noexcept { return name_; }
159
160private:
161 struct Listener final {
162 std::string name;
163 Function callback;
164 std::string task_name;
165 };
166
167 struct ListenersData final {
168 std::unordered_map<FunctionId, Listener, FunctionId::Hash> listeners;
169 OnRemoveCallback on_listener_removal;
170 };
171
172 void RemoveListener(FunctionId id, UnsubscribingKind kind) noexcept final {
173 engine::TaskCancellationBlocker blocker;
174 auto data = data_.Lock();
175 auto& listeners = data->listeners;
176 const auto iter = listeners.find(id);
177
178 if (iter == listeners.end()) {
179 impl::ReportNotSubscribed(Name());
180 return;
181 }
182
183 if (kind == UnsubscribingKind::kAutomatic) {
184 if (!data->on_listener_removal) {
185 impl::ReportUnsubscribingAutomatically(name_, iter->second.name);
186 }
187
188 if constexpr (impl::kCheckSubscriptionUB) {
189 // Fake listener call to check
190 impl::CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing(
191 data->on_listener_removal, iter->second.callback, name_, iter->second.name
192 );
193 }
194 }
195 listeners.erase(iter);
196 }
197
198 AsyncEventSubscriberScope DoAddListener(FunctionId id, std::string_view name, Function&& func) final {
199 auto data = data_.Lock();
200 auto& listeners = data->listeners;
201 auto task_name = impl::MakeAsyncChannelName(name_, name);
202 const auto [iterator, success] =
203 listeners.emplace(id, Listener{std::string{name}, std::move(func), std::move(task_name)});
204 if (!success) impl::ReportAlreadySubscribed(Name(), name);
205 return AsyncEventSubscriberScope(*this, id);
206 }
207
208 const std::string name_;
209 concurrent::Variable<ListenersData> data_;
210 mutable engine::Mutex event_mutex_;
211};
212
213} // namespace concurrent
214
215USERVER_NAMESPACE_END