Commit f20cd436 authored by Dominik Charousset's avatar Dominik Charousset

Merge branch 'topic/neverlord/metric-instances'

parents a58cc0b2 052e3b60
......@@ -15,6 +15,9 @@ is based on [Keep a Changelog](https://keepachangelog.com).
the closing parenthesis.
- The JSON reader now automatically widens integers to doubles as necessary.
- Module options (e.g. for the `middleman`) now show up in `--long-help` output.
- Fix undefined behavior in the Qt group chat example (#1336).
- The `..._instance` convenience functions on the registry metric now properly
support `double` metrics and histograms.
### Changed
......
......@@ -121,7 +121,7 @@ private:
} // namespace caf
namespace caf::detail {
template <class F>
template <class F, bool IsSingleShot>
struct default_action_impl : detail::atomic_ref_counted, action::impl {
std::atomic<action::state> state_;
F f_;
......@@ -144,11 +144,12 @@ struct default_action_impl : detail::atomic_ref_counted, action::impl {
}
void run() override {
// Note: we do *not* set the state to disposed after running the function
// object. This allows the action to re-register itself when needed, e.g.,
// to implement time-based loops.
if (state_.load() == action::state::scheduled) {
f_();
if constexpr (IsSingleShot)
state_ = action::state::disposed;
// else: allow the action to re-register itself when needed by *not*
// setting the state to disposed, e.g., to implement time loops.
}
}
......@@ -177,7 +178,15 @@ namespace caf {
/// @param f The body for the action.
template <class F>
action make_action(F f) {
using impl_t = detail::default_action_impl<F>;
using impl_t = detail::default_action_impl<F, false>;
return action{make_counted<impl_t>(std::move(f))};
}
/// Convenience function for creating an @ref action from a function object.
/// @param f The body for the action.
template <class F>
action make_single_shot_action(F f) {
using impl_t = detail::default_action_impl<F, true>;
return action{make_counted<impl_t>(std::move(f))};
}
......
......@@ -47,7 +47,7 @@ public:
g(static_cast<const error&>(std::get<error>(cp->value)));
}
};
auto cb_action = make_action(std::move(cb));
auto cb_action = make_single_shot_action(std::move(cb));
auto event = typename cell_type::event{ctx_, cb_action};
bool fire_immediately = false;
{ // Critical section.
......@@ -115,6 +115,16 @@ public:
return {ctx, cell_};
}
/// Queries whether the result of the asynchronous computation is still
/// pending, i.e., neither `set_value` nor `set_error` has been called on the
/// @ref promise.
/// @pre `valid()`
bool pending() const {
CAF_ASSERT(valid());
std::unique_lock guard{cell_->mtx};
return std::holds_alternative<none_t>(cell_->value);
}
private:
using cell_ptr = std::shared_ptr<detail::async_cell<T>>;
......
......@@ -19,16 +19,25 @@ template <class T>
class promise {
public:
promise(promise&&) noexcept = default;
promise(const promise&) noexcept = default;
promise& operator=(promise&&) noexcept = default;
promise& operator=(const promise&) noexcept = default;
promise(const promise& other) noexcept : promise(other.cell_) {
// nop
}
promise& operator=(const promise& other) noexcept {
promise copy{other};
cell_.swap(copy.cell_);
return *this;
}
promise() : cell_(std::make_shared<cell_type>()) {
// nop
}
~promise() {
if (cell_) {
if (valid()) {
auto& cnt = cell_->promises;
if (cnt == 1 || cnt.fetch_sub(1, std::memory_order_acq_rel) == 1) {
typename cell_type::event_list events;
......@@ -59,7 +68,7 @@ public:
/// @pre `valid()`
void set_value(T value) {
if (cell_) {
if (valid()) {
do_set(value);
cell_ = nullptr;
}
......@@ -67,7 +76,7 @@ public:
/// @pre `valid()`
void set_error(error reason) {
if (cell_) {
if (valid()) {
do_set(reason);
cell_ = nullptr;
}
......@@ -82,7 +91,7 @@ private:
using cell_type = detail::async_cell<T>;
using cell_ptr = std::shared_ptr<cell_type>;
explicit promise(cell_type cell) : cell_(std::move(cell)) {
explicit promise(cell_ptr cell) noexcept : cell_(std::move(cell)) {
CAF_ASSERT(cell_ != nullptr);
cell_->promises.fetch_add(1, std::memory_order_relaxed);
}
......
......@@ -36,11 +36,12 @@ public:
~actor_widget() {
if (companion_)
self()->cleanup(error{}, &dummy_);
self()->cleanup(error{}, &execution_unit_);
}
void init(actor_system& system) {
alive_ = true;
execution_unit_.system_ptr(&system);
companion_ = actor_cast<strong_actor_ptr>(system.spawn<actor_companion>());
self()->on_enqueue([=](mailbox_element_ptr ptr) {
qApp->postEvent(this, new event_type(std::move(ptr)));
......@@ -66,7 +67,7 @@ public:
if (event->type() == static_cast<QEvent::Type>(EventId)) {
auto ptr = dynamic_cast<event_type*>(event);
if (ptr && alive_) {
switch (self()->activate(&dummy_, *(ptr->mptr))) {
switch (self()->activate(&execution_unit_, *(ptr->mptr))) {
default:
break;
};
......@@ -89,7 +90,7 @@ public:
}
private:
scoped_execution_unit dummy_;
scoped_execution_unit execution_unit_;
strong_actor_ptr companion_;
bool alive_;
};
......
......@@ -136,8 +136,9 @@ public:
gauge_instance(std::string_view prefix, std::string_view name,
span_t<label_view> labels, std::string_view helptext,
std::string_view unit = "1", bool is_sum = false) {
auto fptr = gauge_family<ValueType>(prefix, name, labels, helptext, unit,
is_sum);
auto label_names = get_label_names(labels);
auto fptr = gauge_family<ValueType>(prefix, name, label_names, helptext,
unit, is_sum);
return fptr->get_or_add(labels);
}
......@@ -228,27 +229,6 @@ public:
is_sum);
}
/// @copydoc counter_family
template <class ValueType = int64_t>
metric_family_impl<counter<ValueType>>*
counter_family(std::string_view prefix, std::string_view name,
span_t<label_view> labels, std::string_view helptext,
std::string_view unit = "1", bool is_sum = false) {
using counter_type = counter<ValueType>;
using family_type = metric_family_impl<counter_type>;
std::unique_lock<std::mutex> guard{families_mx_};
if (auto ptr = fetch(prefix, name)) {
assert_properties(ptr, counter_type::runtime_type, labels, unit, is_sum);
return static_cast<family_type*>(ptr);
}
auto ptr = std::make_unique<family_type>(
std::string{prefix}, std::string{name}, to_sorted_vec(labels),
std::string{helptext}, std::string{unit}, is_sum);
auto result = ptr.get();
families_.emplace_back(std::move(ptr));
return result;
}
/// Returns a counter. Creates all objects lazily if necessary, but fails
/// if the full name already belongs to a different family.
/// @param prefix The prefix (namespace) this family belongs to. Usually the
......@@ -269,8 +249,9 @@ public:
counter_instance(std::string_view prefix, std::string_view name,
span_t<label_view> labels, std::string_view helptext,
std::string_view unit = "1", bool is_sum = false) {
auto fptr = counter_family<ValueType>(prefix, name, labels, helptext, unit,
is_sum);
auto label_names = get_label_names(labels);
auto fptr = counter_family<ValueType>(prefix, name, label_names, helptext,
unit, is_sum);
return fptr->get_or_add(labels);
}
......@@ -419,8 +400,10 @@ public:
span_t<label_view> labels, span_t<ValueType> upper_bounds,
std::string_view helptext, std::string_view unit = "1",
bool is_sum = false) {
auto fptr = histogram_family<ValueType>(prefix, name, labels, upper_bounds,
helptext, unit, is_sum);
auto label_names = get_label_names(labels);
auto fptr = histogram_family<ValueType>(prefix, name, label_names,
upper_bounds, helptext, unit,
is_sum);
return fptr->get_or_add(labels);
}
......@@ -432,8 +415,8 @@ public:
span_t<ValueType> upper_bounds, std::string_view helptext,
std::string_view unit = "1", bool is_sum = false) {
span_t<label_view> lbls{labels.begin(), labels.size()};
return histogram_instance(prefix, name, lbls, upper_bounds, helptext, unit,
is_sum);
return histogram_instance<ValueType>(prefix, name, lbls, upper_bounds,
helptext, unit, is_sum);
}
/// Returns a histogram metric singleton, i.e., the single instance of a
......@@ -489,6 +472,8 @@ private:
metric_family* fetch(const std::string_view& prefix,
const std::string_view& name);
static std::vector<std::string_view> get_label_names(span_t<label_view> xs);
static std::vector<std::string> to_sorted_vec(span_t<std::string_view> xs);
static std::vector<std::string> to_sorted_vec(span_t<label_view> xs);
......
......@@ -410,6 +410,7 @@ CAF_BEGIN_TYPE_ID_BLOCK(core_module, 0)
CAF_ADD_TYPE_ID(core_module, (caf::timestamp))
CAF_ADD_TYPE_ID(core_module, (caf::unit_t))
CAF_ADD_TYPE_ID(core_module, (caf::uri))
CAF_ADD_TYPE_ID(core_module, (caf::uuid))
CAF_ADD_TYPE_ID(core_module, (caf::weak_actor_ptr))
CAF_ADD_TYPE_ID(core_module, (std::vector<caf::actor>) )
CAF_ADD_TYPE_ID(core_module, (std::vector<caf::actor_addr>) )
......
......@@ -29,6 +29,7 @@
#include "caf/timestamp.hpp"
#include "caf/unit.hpp"
#include "caf/uri.hpp"
#include "caf/uuid.hpp"
namespace caf::core {
......
......@@ -63,6 +63,15 @@ metric_family* metric_registry::fetch(const std::string_view& prefix,
return nullptr;
}
std::vector<std::string_view>
metric_registry::get_label_names(span_t<label_view> xs) {
std::vector<std::string_view> result;
result.reserve(xs.size());
for (auto& x : xs)
result.push_back(x.name());
return result;
}
std::vector<std::string>
metric_registry::to_sorted_vec(span<const std::string_view> xs) {
std::vector<std::string> result;
......
......@@ -8,6 +8,7 @@
#include "core-test.hpp"
#include "caf/flow/scoped_coordinator.hpp"
#include "caf/scheduled_actor/flow.hpp"
using namespace caf;
......@@ -71,4 +72,55 @@ SCENARIO("actors can observe futures") {
}
}
SCENARIO("never setting a value or an error breaks the promises") {
GIVEN("multiple promises that point to the same cell") {
WHEN("the last promise goes out of scope") {
THEN("the future reports a broken promise") {
using promise_t = async::promise<int32_t>;
using future_t = async::future<int32_t>;
future_t fut;
{
auto uut = promise_t{};
fut = uut.get_future();
CHECK(fut.pending());
{
// copy ctor
promise_t cpy{uut};
CHECK(fut.pending());
// move ctor
promise_t mv{std::move(cpy)};
CHECK(fut.pending());
{
// copy assign
promise_t cpy2;
cpy2 = mv;
CHECK(fut.pending());
// move assign
promise_t mv2;
mv2 = std::move(mv);
CHECK(fut.pending());
}
CHECK(fut.pending());
}
CHECK(fut.pending());
}
CHECK(!fut.pending());
auto ctx = flow::scoped_coordinator::make();
size_t observed_events = 0;
fut.bind_to(ctx.get()).then(
[&observed_events](int32_t) {
++observed_events;
FAIL("unexpected value");
},
[&observed_events](const error& err) {
++observed_events;
CHECK_EQ(err, make_error(sec::broken_promise));
});
ctx->run();
CHECK_EQ(observed_events, 1u);
}
}
}
}
END_FIXTURE_SCOPE()
......@@ -80,7 +80,7 @@ struct test_collector {
};
struct fixture {
metric_registry registry;
metric_registry reg;
test_collector collector;
};
......@@ -90,10 +90,10 @@ BEGIN_FIXTURE_SCOPE(fixture)
CAF_TEST(registries lazily create metrics) {
std::vector<int64_t> upper_bounds{1, 2, 4, 8};
auto f = registry.gauge_family("caf", "running-actors", {"var1", "var2"},
"How many actors are currently running?");
auto g = registry.histogram_family("caf", "response-time", {"var1", "var2"},
upper_bounds, "How long take requests?");
auto f = reg.gauge_family("caf", "running-actors", {"var1", "var2"},
"How many actors are currently running?");
auto g = reg.histogram_family("caf", "response-time", {"var1", "var2"},
upper_bounds, "How long take requests?");
std::vector<label_view> v1{{"var1", "foo"}, {"var2", "bar"}};
std::vector<label_view> v1_reversed{{"var2", "bar"}, {"var1", "foo"}};
std::vector<label_view> v2{{"var1", "bar"}, {"var2", "foo"}};
......@@ -113,24 +113,21 @@ CAF_TEST(registries lazily create metrics) {
}
CAF_TEST(registries allow users to collect all registered metrics) {
auto fb = registry.gauge_family("foo", "bar", {},
"Some value without labels.", "seconds");
auto sv = registry.gauge_family("some", "value", {"a", "b"},
"Some (total) value with two labels.", "1",
true);
auto ov = registry.gauge_family("other", "value", {"x"},
"Some (total) seconds with one label.",
"seconds", true);
auto ra = registry.gauge_family("caf", "running-actors", {"node"},
"How many actors are running?");
auto ms = registry.gauge_family("caf", "mailbox-size", {"name"},
"How full is the mailbox?");
auto fb = reg.gauge_family("foo", "bar", {}, "Some value without labels.",
"seconds");
auto sv = reg.gauge_family("some", "value", {"a", "b"},
"Some (total) value with two labels.", "1", true);
auto ov = reg.gauge_family("other", "value", {"x"},
"Some (total) seconds with one label.", "seconds",
true);
auto ra = reg.gauge_family("caf", "running-actors", {"node"},
"How many actors are running?");
auto ms = reg.gauge_family("caf", "mailbox-size", {"name"},
"How full is the mailbox?");
MESSAGE("the registry always returns the same family object");
CHECK_EQ(fb, registry.gauge_family("foo", "bar", {}, "", "seconds"));
CHECK_EQ(sv,
registry.gauge_family("some", "value", {"a", "b"}, "", "1", true));
CHECK_EQ(sv,
registry.gauge_family("some", "value", {"b", "a"}, "", "1", true));
CHECK_EQ(fb, reg.gauge_family("foo", "bar", {}, "", "seconds"));
CHECK_EQ(sv, reg.gauge_family("some", "value", {"a", "b"}, "", "1", true));
CHECK_EQ(sv, reg.gauge_family("some", "value", {"b", "a"}, "", "1", true));
MESSAGE("families always return the same metric object for given labels");
CHECK_EQ(fb->get_or_add({}), fb->get_or_add({}));
CHECK_EQ(sv->get_or_add({{"a", "1"}, {"b", "2"}}),
......@@ -143,7 +140,7 @@ CAF_TEST(registries allow users to collect all registered metrics) {
ra->get_or_add({{"node", "localhost"}})->value(42);
ms->get_or_add({{"name", "printer"}})->value(3);
ms->get_or_add({{"name", "parser"}})->value(12);
registry.collect(collector);
reg.collect(collector);
CHECK_EQ(collector.result, R"(
foo.bar.seconds 123
some.value.total{a="1",b="2"} 12
......@@ -168,10 +165,10 @@ CAF_TEST(buckets for histograms are configurable via runtime settings) {
std::vector<int64_t> alternative_upper_bounds{10, 20, 30};
put(cfg, "caf.response-time.buckets", upper_bounds);
put(cfg, "caf.response-time.var1=foo.buckets", alternative_upper_bounds);
registry.config(&cfg);
auto hf = registry.histogram_family("caf", "response-time", {"var1", "var2"},
default_upper_bounds,
"How long take requests?");
reg.config(&cfg);
auto hf = reg.histogram_family("caf", "response-time", {"var1", "var2"},
default_upper_bounds,
"How long take requests?");
CHECK_EQ(hf->config(), get_if<settings>(&cfg, "caf.response-time"));
CHECK_EQ(hf->extra_setting(), upper_bounds);
auto h1 = hf->get_or_add({{"var1", "bar"}, {"var2", "baz"}});
......@@ -181,15 +178,92 @@ CAF_TEST(buckets for histograms are configurable via runtime settings) {
CHECK_EQ(bounds(h2->buckets()), alternative_upper_bounds);
}
CAF_TEST(counter_instance is a shortcut for using the family manually) {
auto fptr = registry.counter_family("http", "requests", {"method"},
"Number of HTTP requests.", "seconds",
true);
auto count = fptr->get_or_add({{"method", "put"}});
auto count2
= registry.counter_instance("http", "requests", {{"method", "put"}},
"Number of HTTP requests.", "seconds", true);
CHECK_EQ(count, count2);
SCENARIO("instance methods provide a shortcut for using the family manually") {
GIVEN("an int counter family with at least one label dimension") {
WHEN("calling counter_instance on the registry") {
THEN("calling get_or_add on the family object returns the same pointer") {
auto fp = reg.counter_family("http", "requests", {"method"},
"Number of HTTP requests.", "seconds",
true);
auto p1 = fp->get_or_add({{"method", "put"}});
auto p2 = reg.counter_instance("http", "requests", {{"method", "put"}},
"Number of HTTP requests.", "seconds",
true);
CHECK_EQ(p1, p2);
}
}
}
GIVEN("an int gauge family with at least one label dimension") {
WHEN("calling gauge_instance on the registry") {
THEN("calling get_or_add on the family object returns the same pointer") {
auto fp = reg.gauge_family("db", "pending", {"operation"},
"Pending DB operations.");
auto p1 = fp->get_or_add({{"operation", "update"}});
auto p2 = reg.gauge_instance("db", "pending", {{"operation", "update"}},
"Pending DB operations.");
CHECK_EQ(p1, p2);
}
}
}
GIVEN("an int histogram family with at least one label dimension") {
WHEN("calling histogram_instance on the registry") {
THEN("calling get_or_add on the family object returns the same pointer") {
std::vector<int64_t> upper_bounds{1, 2, 3, 5, 7};
auto fp = reg.histogram_family("db", "query-results", {"operation"},
upper_bounds, "Results per query.");
auto p1 = fp->get_or_add({{"operation", "update"}});
auto p2 = reg.histogram_instance("db", "query-results",
{{"operation", "update"}},
upper_bounds, "Results per query.");
CHECK_EQ(p1, p2);
}
}
}
GIVEN("a double counter family with at least one label dimension") {
WHEN("calling counter_instance on the registry") {
THEN("calling get_or_add on the family object returns the same pointer") {
auto fp = reg.counter_family<double>("db", "cpu-usage", {"operation"},
"Total CPU time by query type.",
"seconds", true);
auto p1 = fp->get_or_add({{"operation", "update"}});
auto p2 = reg.counter_instance<double>("db", "cpu-usage",
{{"operation", "update"}},
"Total CPU time by query type.",
"seconds", true);
CHECK_EQ(p1, p2);
}
}
}
GIVEN("a double gauge family with at least one label dimension") {
WHEN("calling gauge_instance on the registry") {
THEN("calling get_or_add on the family object returns the same pointer") {
auto fp = reg.gauge_family<double>("sensor", "water-level",
{"location"},
"Water level by location.");
auto p1 = fp->get_or_add({{"location", "tank-1"}});
auto p2 = reg.gauge_instance<double>("sensor", "water-level",
{{"location", "tank-1"}},
"Water level by location.");
CHECK_EQ(p1, p2);
}
}
}
GIVEN("a double histogram family with at least one label dimension") {
WHEN("calling histogram_instance on the registry") {
THEN("calling get_or_add on the family object returns the same pointer") {
std::vector<double> upper_bounds{1, 2, 3, 5, 7};
auto fp = reg.histogram_family<double>("db", "query-duration",
{"operation"}, upper_bounds,
"Query processing time.");
auto p1 = fp->get_or_add({{"operation", "update"}});
auto p2 = reg.histogram_instance<double>("db", "query-duration",
{{"operation", "update"}},
upper_bounds,
"Query processing time.");
CHECK_EQ(p1, p2);
}
}
}
}
SCENARIO("metric registries can merge families from other registries") {
......@@ -198,12 +272,10 @@ SCENARIO("metric registries can merge families from other registries") {
auto foo_bar = tmp.counter_singleton("foo", "bar", "test metric");
auto bar_foo = tmp.counter_singleton("bar", "foo", "test metric");
WHEN("merging the registry into another one") {
registry.merge(tmp);
reg.merge(tmp);
THEN("all metrics move into the new location") {
CHECK_EQ(foo_bar,
registry.counter_singleton("foo", "bar", "test metric"));
CHECK_EQ(bar_foo,
registry.counter_singleton("bar", "foo", "test metric"));
CHECK_EQ(foo_bar, reg.counter_singleton("foo", "bar", "test metric"));
CHECK_EQ(bar_foo, reg.counter_singleton("bar", "foo", "test metric"));
tmp.collect(collector);
CHECK(collector.result.empty());
}
......
......@@ -12,7 +12,7 @@ namespace caf::io::basp {
/// @{
/// The current BASP version. Note: BASP is not backwards compatible.
constexpr uint64_t version = 4;
constexpr uint64_t version = 5;
/// @}
......
......@@ -66,15 +66,11 @@ middleman::~middleman() {
void middleman::start() {
if (!get_or(config(), "caf.middleman.manual-multiplexing", false)) {
mpx_thread_ = std::thread{[this] {
CAF_SET_LOGGER_SYS(&sys_);
detail::set_thread_name("caf.net.mpx");
sys_.thread_started();
mpx_thread_ = sys_.launch_thread("caf.net.mpx", [this] {
mpx_->set_thread_id();
launch_background_tasks(sys_);
mpx_->run();
sys_.thread_terminates();
}};
});
} else {
mpx_->set_thread_id();
}
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment