userver: concurrent::AsyncEventChannel< Args > Class Template Reference
Loading...
Searching...
No Matches
concurrent::AsyncEventChannel< Args > Class Template Reference

#include <userver/concurrent/async_event_channel.hpp>

Detailed Description

template<typename... Args>
class concurrent::AsyncEventChannel< Args >

AsyncEventChannel is an in-process pub-sub with strict FIFO serialization, i.e. only after the event was processed a new event may appear for processing, same listener is never called concurrently.

Example usage:

enum class WeatherKind { kSunny, kRainy };
class WeatherStorage final {
public:
explicit WeatherStorage(WeatherKind value)
: value_(value),
channel_("weather")
{}
WeatherKind Get() const { return value_.load(); }
concurrent::AsyncEventSource<WeatherKind>& GetSource() { return channel_; }
template <typename Class>
void UpdateAndListen(
utils::ResourceScopeStorage& scopes,
Class* obj,
std::string_view name,
void (Class::*func)(WeatherKind)
) {
channel_.DoUpdateAndListen(scopes, obj, name, func, [this, obj, func] { (obj->*func)(Get()); });
}
void Set(WeatherKind value) {
value_.store(value);
channel_.SendEvent(value);
}
private:
std::atomic<WeatherKind> value_;
concurrent::AsyncEventChannel<WeatherKind> channel_;
};
enum class CoatKind { kJacket, kRaincoat };
class CoatStorage final {
public:
explicit CoatStorage(utils::ResourceScopeStorage& scopes, WeatherStorage& weather_storage) {
weather_storage.UpdateAndListen(scopes, this, "coats", &CoatStorage::OnWeatherUpdate);
}
CoatKind Get() const { return value_.load(); }
private:
void OnWeatherUpdate(WeatherKind weather) { value_.store(ComputeCoat(weather)); }
static CoatKind ComputeCoat(WeatherKind weather);
std::atomic<CoatKind> value_{};
};
UTEST(AsyncEventChannel, UpdateAndListenSample) {
WeatherStorage weather_storage(WeatherKind::kSunny);
const utils::WithResourceScopes<CoatStorage> coat_storage(std::in_place, weather_storage);
EXPECT_EQ(coat_storage->Get(), CoatKind::kJacket);
weather_storage.Set(WeatherKind::kRainy);
EXPECT_EQ(coat_storage->Get(), CoatKind::kRaincoat);
}

Definition at line 83 of file async_event_channel.hpp.

Inheritance diagram for concurrent::AsyncEventChannel< Args >:

Public Types

using Function = typename AsyncEventSource<Args...>::Function
using OnRemoveCallback = std::function<void(const Function&)>

Public Member Functions

 AsyncEventChannel (std::string_view name)
 The primary constructor.
 AsyncEventChannel (std::string_view name, OnRemoveCallback on_listener_removal)
 Constructs a channel with a debug check for listener removal.
template<typename UpdaterFunc>
void DoUpdateAndListen (utils::ResourceScopeStorage &scopes, FunctionId id, std::string_view name, Function &&func, UpdaterFunc &&updater)
 Processes the current value and subscribes to subsequent events for the lifetime of scopes.
template<typename Class, typename UpdaterFunc>
void DoUpdateAndListen (utils::ResourceScopeStorage &scopes, Class *obj, std::string_view name, void(Class::*func)(Args...), UpdaterFunc &&updater)
void SendEvent (Args... args) const
const std::string & Name () const noexcept
void AddListener (utils::ResourceScopeStorage &scopes, Class *obj, std::string_view name, void(Class::*func)(Args...))
 Subscribes to updates from this event source.

Member Typedef Documentation

◆ Function

template<typename... Args>
using concurrent::AsyncEventChannel< Args >::Function = typename AsyncEventSource<Args...>::Function

Definition at line 85 of file async_event_channel.hpp.

◆ OnRemoveCallback

template<typename... Args>
using concurrent::AsyncEventChannel< Args >::OnRemoveCallback = std::function<void(const Function&)>

Definition at line 86 of file async_event_channel.hpp.

Constructor & Destructor Documentation

◆ AsyncEventChannel() [1/2]

template<typename... Args>
concurrent::AsyncEventChannel< Args >::AsyncEventChannel ( std::string_view name)
inlineexplicit

The primary constructor.

Parameters
nameused for diagnostic purposes and is also accessible with Name

Definition at line 90 of file async_event_channel.hpp.

◆ AsyncEventChannel() [2/2]

template<typename... Args>
concurrent::AsyncEventChannel< Args >::AsyncEventChannel ( std::string_view name,
OnRemoveCallback on_listener_removal )
inline

Constructs a channel with a debug check for listener removal.

The callback receives the listener function when its subscription ends and can invoke it to check the lifetime of the captured data.

Note
Works only in debug mode.
Warning
Data captured by on_listener_removal function must be valid until the AsyncEventChannel object is completely destroyed.

Example usage:

auto on_remove = [](std::function<void(int)> func) { func(1); };
concurrent::AsyncEventChannel<int> channel("channel", on_remove);
struct Recorder {
Recorder(utils::ResourceScopeStorage& scopes, concurrent::AsyncEventSource<int>& source, int& value)
: value(value)
{
source.AddListener(scopes, concurrent::FunctionId(this), "recorder", [this](int new_value) {
this->value = new_value;
});
}
int& value;
};
int value = 0;
{
utils::WithResourceScopes<Recorder> sub(std::in_place, channel, value);
}
if constexpr (concurrent::impl::kCheckSubscriptionUB) {
EXPECT_EQ(value, 1);
} else {
EXPECT_EQ(value, 0);
}
Parameters
nameused for diagnostic purposes and is also accessible with Name
on_listener_removalthe callback used for check
See also
impl::CheckDataUsedByCallbackHasNotBeenDestroyedBeforeUnsubscribing

Definition at line 112 of file async_event_channel.hpp.

Member Function Documentation

◆ AddListener()

void concurrent::AsyncEventSource< Args >::AddListener ( utils::ResourceScopeStorage & scopes,
Class * obj,
std::string_view name,
void(Class::* func )(Args...) )
inlineinherited

Subscribes to updates from this event source.

The listener won't be called immediately.

Example usage:

class WeatherRecorder final {
public:
WeatherRecorder(utils::ResourceScopeStorage& scopes, WeatherStorage& weather_storage) {
weather_storage.GetSource()
.AddListener(scopes, concurrent::FunctionId(this), "recorder", [this](WeatherKind weather) {
recorded_weather.push_back(weather);
});
}
std::vector<WeatherKind> recorded_weather;
};
UTEST(AsyncEventChannel, AddListenerSample) {
WeatherStorage weather_storage(WeatherKind::kSunny);
utils::WithResourceScopes<WeatherRecorder> recorder(std::in_place, weather_storage);
weather_storage.Set(WeatherKind::kRainy);
weather_storage.Set(WeatherKind::kSunny);
weather_storage.Set(WeatherKind::kSunny);
EXPECT_EQ(recorder->recorded_weather, (std::vector{WeatherKind::kRainy, WeatherKind::kSunny, WeatherKind::kSunny}));
}

Subscription starts after utils::ResourceScopeStorage::AfterConstruction. Events sent before that are not delivered to the listener. Unsubscribe runs in utils::ResourceScopeStorage::BeforeDestruction. This event source must outlive the resource scopes.

Parameters
scopesstorage that owns the subscription lifetime. See where to obtain scopes.
objthe subscriber, which is the owner of the listener method, and is also used as the unique identifier of the subscription for this AsyncEventSource
namethe name of the subscriber, for diagnostic purposes
functhe listener method, usually called On<DataName>Update, e.g. OnConfigUpdate or OnCacheUpdate

Possible races when using AddListener

Manually processing the current value and subscribing in separate steps introduces a race. The following pseudocode assumes that scopes is already active:

OnCacheUpdate(cache.Get());
source.AddListener(scopes, this, "cache-listener", &MyClass::OnCacheUpdate);

An update between reading the cache and subscribing is missed. Reversing the order also introduces a race:

source.AddListener(scopes, this, "cache-listener", &MyClass::OnCacheUpdate);
OnCacheUpdate(cache.Get());

The event callback may run concurrently with the manual call, possibly processing the same cache value twice.

To process the current value and then listen to updates, use UpdateAndListen on the concrete data source, e.g. components::CachingComponentBase::UpdateAndListen. If only concurrent::AsyncEventChannel is available, use concurrent::AsyncEventChannel::DoUpdateAndListen.

Definition at line 101 of file async_event_source.hpp.

◆ DoUpdateAndListen() [1/2]

template<typename... Args>
template<typename Class, typename UpdaterFunc>
void concurrent::AsyncEventChannel< Args >::DoUpdateAndListen ( utils::ResourceScopeStorage & scopes,
Class * obj,
std::string_view name,
void(Class::* func )(Args...),
UpdaterFunc && updater )
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
scopesstorage that owns the subscription lifetime. See where to obtain scopes.
objobject on which to invoke the callback.
namesubscriber name.
funcmember function to invoke.
updatercallback that reads the current state.

Definition at line 178 of file async_event_channel.hpp.

◆ DoUpdateAndListen() [2/2]

template<typename... Args>
template<typename UpdaterFunc>
void concurrent::AsyncEventChannel< Args >::DoUpdateAndListen ( utils::ResourceScopeStorage & scopes,
FunctionId id,
std::string_view name,
Function && func,
UpdaterFunc && updater )
inline

Processes the current value and subscribes to subsequent events for the lifetime of scopes.

Synchronously calls updater and records the channel's event generation. When the scope is entered, updater is called again if an event was sent during construction, then func is subscribed atomically with that check. Unsubscribes on scope exit.

Warning
updater is not only invoked inline. It is stored and may run again after this call returns, when the scope is entered. Do not capture locals by reference: copy the pointers and values the updater needs (for example obj and func) and capture this explicitly.
Parameters
scopesstorage that owns the subscription lifetime. See where to obtain scopes.
idsubscriber identity.
namesubscriber name.
funccallback invoked for channel events.
updatercallback that reads the current state.

Definition at line 134 of file async_event_channel.hpp.

◆ Name()

template<typename... Args>
const std::string & concurrent::AsyncEventChannel< Args >::Name ( ) const
inlinenoexcept
Returns
the name of this event channel

Definition at line 245 of file async_event_channel.hpp.

◆ SendEvent()

template<typename... Args>
void concurrent::AsyncEventChannel< Args >::SendEvent ( Args... args) const
inline

Send the next event and wait until all the listeners process it.

Strict FIFO serialization is guaranteed, i.e. only after this event is processed a new event may be delivered for the subscribers, same listener/subscriber is never called concurrently.

Definition at line 199 of file async_event_channel.hpp.


The documentation for this class was generated from the following file: