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
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
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// Data used by the callback must remain valid until the subscription scope is destroyed.
55template <typename Func>
56void CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing(
57 std::function<void(const Func&)>& on_listener_removal,
58 const Func& listener_func,
59 std::string_view channel_name,
60 std::string_view listener_name
61) noexcept {
62 if (!on_listener_removal) {
63 return;
64 }
65 try {
66 on_listener_removal(listener_func);
67 } catch (const std::exception& e) {
68 ReportErrorWhileUnsubscribing(channel_name, listener_name, e.what());
69 }
70}
71
72} // namespace impl
73
82template <typename... Args>
83class AsyncEventChannel : public AsyncEventSource<Args...> {
84public:
85 using Function = typename AsyncEventSource<Args...>::Function;
86 using OnRemoveCallback = std::function<void(const Function&)>;
87
90 explicit AsyncEventChannel(std::string_view name)
91 : name_(name),
92 data_(ListenersData{{}, {}})
93 {}
94
112 AsyncEventChannel(std::string_view name, OnRemoveCallback on_listener_removal)
113 : name_(name),
114 data_(ListenersData{{}, std::move(on_listener_removal)})
115 {}
116
133 template <typename UpdaterFunc>
136 FunctionId id,
137 std::string_view name,
138 Function&& func,
139 UpdaterFunc&& updater
140 ) {
141 const auto initial_generation = [this, &updater] {
142 const std::shared_lock lock(event_mutex_);
143 updater();
144 return event_generation_;
145 }();
146
147 // The first callback runs synchronously in the constructor, so the subscription
148 // lifetime must be longer than that of other scope types.
149 constexpr utils::ResourceScopeStorage::Priority kPriority{-1};
150 scopes.Register(
151 utils::impl::InternalTag{},
152 kPriority,
153 [this,
154 id,
155 name = std::string{name},
156 initial_generation,
157 func = std::move(func),
158 updater = std::forward<UpdaterFunc>(updater)]() mutable {
159 const std::shared_lock lock(event_mutex_);
160 if (event_generation_ != initial_generation) {
161 updater();
162 }
163 DoAddListener(id, name, std::move(func));
164 using SubscriberScope = typename AsyncEventSource<Args...>::AsyncEventSubscriberScope;
165 return SubscriberScope(utils::impl::InternalTag{}, *this, id);
166 }
167 );
168 }
169
177 template <typename Class, typename UpdaterFunc>
180 Class* obj,
181 std::string_view name,
182 void (Class::*func)(Args...),
183 UpdaterFunc&& updater
184 ) {
186 scopes,
187 FunctionId(obj),
188 name,
189 [obj, func](Args... args) { (obj->*func)(args...); },
190 std::forward<UpdaterFunc>(updater)
191 );
192 }
193
199 void SendEvent(Args... args) const {
200 struct Task {
201 std::shared_ptr<const Listener> listener;
203 };
204 std::vector<Task> tasks;
205
206 std::shared_lock<engine::SharedMutex> tmp_lock;
207 {
208 // Try to obtain unique lock for event_mutex_ to serialize
209 // calls to SendEvent()
210 std::unique_lock lock(event_mutex_);
211 auto data = data_.Lock();
212 ++event_generation_;
213
214 tmp_lock = impl::DowngradeLock(std::move(lock));
215
216 // Now we want to create N subtasks for callbacks,
217 // which must hold event_mutex_'s std::shared_lock.
218 // A naive implementation would create std::shared_lock{event_mutex_} for each subtask,
219 // however, it might deadlock if any parallel SendEvent() is called and is blocked on
220 // event_mutex_.lock(). It happens due to strict prioritization of writers above readers
221 // in SharedMutex: if there is any pending writer, nobody may lock the mutex for read.
222 auto& listeners = data->listeners;
223 tasks.reserve(listeners.size());
224
225 for (const auto& [_, listener] : listeners) {
226 tasks.push_back(Task{
227 listener, // an intentional copy
229 listener->task_name,
230 [&, &callback = listener->callback, sema_lock = std::shared_lock(listener->sema)] {
231 callback(args...);
232 }
233 ),
234 });
235 }
236 }
237 // Unlock data_ here because callbacks may subscribe to this
238
239 for (auto& task : tasks) {
240 impl::WaitForTask(task.listener->name, task.task);
241 }
242 }
243
245 const std::string& Name() const noexcept { return name_; }
246
247private:
248 friend struct impl::AsyncEventChannelTestAccessor;
249
250 struct Listener final {
251 // 'sema' with data_.Lock() are used to synchronize removal 'Listener' from ListenersData::listeners
252 mutable engine::Semaphore sema;
253
254 std::string name;
255 Function callback;
256 std::string task_name;
257
258 Listener(std::string name, Function callback, std::string task_name)
259 : sema(1),
260 name(std::move(name)),
261 callback(std::move(callback)),
262 task_name(std::move(task_name))
263 {}
264 };
265
266 struct ListenersData final {
267 std::unordered_map<FunctionId, std::shared_ptr<const Listener>, FunctionId::Hash> listeners;
268 OnRemoveCallback on_listener_removal;
269 };
270
271 void RemoveListener(FunctionId id) noexcept final {
273 const std::shared_lock lock(event_mutex_);
274 std::shared_ptr<const Listener> listener;
275 OnRemoveCallback on_listener_removal;
276
277 {
278 auto data = data_.Lock();
279 auto& listeners = data->listeners;
280 const auto iter = listeners.find(id);
281
282 if (iter == listeners.end()) {
283 impl::ReportNotSubscribed(Name());
284 return;
285 }
286
287 listener = iter->second;
288
289 on_listener_removal = data->on_listener_removal;
290
291 listeners.erase(iter);
292
293 // Lock and unlock sema under data_.Lock(),
294 // now we're sure that SendEvent() will not trigger listener->callback()
295 (void)std::shared_lock(listener->sema);
296 }
297 // Unlock data_ here to be able to (un)subscribe to *this in listener->callback (in debug)
298 // without deadlock
299
300 if constexpr (impl::kCheckSubscriptionUB) {
301 // Fake listener call to check
302 impl::CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing(
303 on_listener_removal,
304 listener->callback,
305 name_,
306 listener->name
307 );
308 }
309 }
310
311 void DoAddListener(FunctionId id, std::string_view name, Function&& func) final {
312 UASSERT(id);
313
314 auto data = data_.Lock();
315 auto& listeners = data->listeners;
316 auto task_name = impl::MakeAsyncChannelName(name_, name);
317 const auto [iterator, success] = listeners.emplace(
318 id,
319 std::make_shared<const Listener>(std::string{name}, std::move(func), std::move(task_name))
320 );
321 if (!success) {
322 impl::ReportAlreadySubscribed(Name(), name);
323 }
324 }
325
326 const std::string name_;
328
329 // The mutex is unique locked
330 // for new event publishing, and is shared locked for calling callbacks.
331 // If any callback is working, no new event publishing is possible.
332 // It *is* possible to re-subscribe on async channel while another callback
333 // operates.
334 mutable engine::SharedMutex event_mutex_;
335 mutable std::uint64_t event_generation_{0};
336};
337
338} // namespace concurrent
339
340USERVER_NAMESPACE_END