10#include <unordered_map>
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>
22USERVER_NAMESPACE_BEGIN
28void WaitForTask(std::string_view name, engine::
TaskWithResult<
void>& task);
30[[noreturn]]
void ReportAlreadySubscribed(std::string_view channel_name, std::string_view listener_name);
32void ReportNotSubscribed(std::string_view channel_name)
noexcept;
34void ReportUnsubscribingAutomatically(std::string_view channel_name, std::string_view listener_name)
noexcept;
36void ReportErrorWhileUnsubscribing(
37 std::string_view channel_name,
38 std::string_view listener_name,
39 std::string_view error
42std::string MakeAsyncChannelName(std::string_view base, std::string_view name);
44inline constexpr bool kCheckSubscriptionUB =
utils::impl::kEnableAssert;
51template <
typename Func>
52void CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing(
53 std::function<
void(Func&)>& on_listener_removal,
55 std::string_view channel_name,
56 std::string_view listener_name
58 if (!on_listener_removal)
return;
60 on_listener_removal(listener_func);
61 }
catch (
const std::exception& e) {
62 ReportErrorWhileUnsubscribing(channel_name, listener_name, e.what());
76template <
typename... Args>
79 using Function =
typename AsyncEventSource<Args...>::Function;
80 using OnRemoveCallback = std::function<
void(Function&)>;
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));
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(
128 [obj, func](Args... args) { (obj->*func)(args...); },
129 std::forward<UpdaterFunc>(updater)
139 std::lock_guard lock(event_mutex_);
140 auto data = data_.Lock();
141 auto& listeners = data->listeners;
143 std::vector<engine::TaskWithResult<
void>> tasks;
144 tasks.reserve(listeners.size());
146 for (
const auto& [_, listener] : listeners) {
147 tasks.push_back(utils::Async(listener.task_name, [&, &callback = listener.callback] { callback(args...); })
152 for (
const auto& [_, listener] : listeners) {
153 impl::WaitForTask(listener.name, tasks[i++]);
158 const std::string&
Name()
const noexcept {
return name_; }
161 struct Listener
final {
164 std::string task_name;
167 struct ListenersData
final {
168 std::unordered_map<FunctionId, Listener, FunctionId::Hash> listeners;
169 OnRemoveCallback on_listener_removal;
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);
178 if (iter == listeners.end()) {
179 impl::ReportNotSubscribed(Name());
183 if (kind == UnsubscribingKind::kAutomatic) {
184 if (!data->on_listener_removal) {
185 impl::ReportUnsubscribingAutomatically(name_, iter->second.name);
188 if constexpr (impl::kCheckSubscriptionUB) {
190 impl::CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing(
191 data->on_listener_removal, iter->second.callback, name_, iter->second.name
195 listeners.erase(iter);
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);
208 const std::string name_;
209 concurrent::Variable<ListenersData> data_;
210 mutable engine::Mutex event_mutex_;