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,
31 std::string_view listener_name);
32
33void ReportNotSubscribed(std::string_view channel_name) noexcept;
34
35void ReportUnsubscribingAutomatically(std::string_view channel_name,
36 std::string_view listener_name) noexcept;
37
38void ReportErrorWhileUnsubscribing(std::string_view channel_name,
39 std::string_view listener_name,
40 std::string_view error) 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, Func& listener_func,
54 std::string_view channel_name, std::string_view listener_name) noexcept {
55 if (!on_listener_removal) return;
56 try {
57 on_listener_removal(listener_func);
58 } catch (const std::exception& e) {
59 ReportErrorWhileUnsubscribing(channel_name, listener_name, e.what());
60 }
61}
62
63} // namespace impl
64
65/// @ingroup userver_concurrency
66///
67/// AsyncEventChannel is an in-process pub-sub with strict FIFO serialization,
68/// i.e. only after the event was processed a new event may appear for
69/// processing, same listener is never called concurrently.
70///
71/// Example usage:
72/// @snippet concurrent/async_event_channel_test.cpp AsyncEventChannel sample
73template <typename... Args>
74class AsyncEventChannel : public AsyncEventSource<Args...> {
75 public:
76 using Function = typename AsyncEventSource<Args...>::Function;
77 using OnRemoveCallback = std::function<void(Function&)>;
78
79 /// @brief The primary constructor
80 /// @param name used for diagnostic purposes and is also accessible with Name
81 explicit AsyncEventChannel(std::string_view name)
82 : name_(name), data_(ListenersData{{}, {}}) {}
83
84 /// @brief The constructor with `AsyncEventSubscriberScope` usage checking.
85 ///
86 /// The constructor with a callback that is called on listener removal. The
87 /// callback takes a reference to `Function' as input. This is useful for
88 /// checking the lifetime of data captured by the listener update function.
89 ///
90 /// @note Works only in debug mode.
91 ///
92 /// @warning Data captured by `on_listener_removal` function must be valid
93 /// until the `AsyncEventChannel` object is completely destroyed.
94 ///
95 /// Example usage:
96 /// @snippet concurrent/async_event_channel_test.cpp OnListenerRemoval sample
97 ///
98 /// @param name used for diagnostic purposes and is also accessible with Name
99 /// @param on_listener_removal the callback used for check
100 ///
101 /// @see impl::CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing
102 AsyncEventChannel(std::string_view name, OnRemoveCallback on_listener_removal)
104
105 /// @brief For use in `UpdateAndListen` of specific event channels
106 ///
107 /// Atomically calls `updater`, which should invoke `func` with the previously
108 /// sent event, and subscribes to new events as if using AddListener.
109 ///
110 /// @see AsyncEventSource::AddListener
111 template <typename UpdaterFunc>
112 AsyncEventSubscriberScope DoUpdateAndListen(FunctionId id,
113 std::string_view name,
114 Function&& func,
115 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 DoUpdateAndListen(Class* obj, std::string_view name,
124 void (Class::*func)(Args...),
125 UpdaterFunc&& updater) {
126 return DoUpdateAndListen(
127 FunctionId(obj), name,
128 [obj, func](Args... args) { (obj->*func)(args...); },
129 std::forward<UpdaterFunc>(updater));
130 }
131
132 /// Send the next event and wait until all the listeners process it.
133 ///
134 /// Strict FIFO serialization is guaranteed, i.e. only after this event is
135 /// processed a new event may be delivered for the subscribers, same
136 /// listener/subscriber is never called concurrently.
137 void SendEvent(Args... args) const {
138 std::lock_guard lock(event_mutex_);
139 auto data = data_.Lock();
140 auto& listeners = data->listeners;
141
142 std::vector<engine::TaskWithResult<void>> tasks;
143 tasks.reserve(listeners.size());
144
145 for (const auto& [_, listener] : listeners) {
146 tasks.push_back(utils::Async(
147 listener.task_name,
148 [&, &callback = listener.callback] { callback(args...); }));
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
160 private:
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_,
192 iter->second.name);
193 }
194 }
195 listeners.erase(iter);
196 }
197
198 AsyncEventSubscriberScope DoAddListener(FunctionId id, std::string_view name,
199 Function&& func) final {
200 auto data = data_.Lock();
201 auto& listeners = data->listeners;
202 auto task_name = impl::MakeAsyncChannelName(name_, name);
203 const auto [iterator, success] = listeners.emplace(
204 id, Listener{std::string{name}, std::move(func), std::move(task_name)});
205 if (!success) impl::ReportAlreadySubscribed(Name(), name);
206 return AsyncEventSubscriberScope(*this, id);
207 }
208
209 const std::string name_;
210 concurrent::Variable<ListenersData> data_;
211 mutable engine::Mutex event_mutex_;
212};
213
214} // namespace concurrent
215
216USERVER_NAMESPACE_END