diff --git a/.clang-format b/.clang-format index 50efaa6a..c45278f7 100644 --- a/.clang-format +++ b/.clang-format @@ -1,62 +1,41 @@ ---- -AccessModifierOffset: -2 +--- +AccessModifierOffset: '-2' AlignAfterOpenBracket: Align AlignEscapedNewlines: Right -AlignOperands: true -AllowAllParametersOfDeclarationOnNextLine: false -AllowShortBlocksOnASingleLine: false -AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: None -AllowShortIfStatementsOnASingleLine: false -AllowShortLoopsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: 'false' AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: false -AlwaysBreakTemplateDeclarations: Yes -BinPackArguments: true -BinPackParameters: true -BreakBeforeBinaryOperators: All +AlwaysBreakTemplateDeclarations: 'Yes' +BreakBeforeBinaryOperators: NonAssignment BreakBeforeBraces: Attach -BreakBeforeTernaryOperators: true +BreakBeforeTernaryOperators: 'true' BreakConstructorInitializers: BeforeColon BreakInheritanceList: BeforeColon -CompactNamespaces: false -ConstructorInitializerAllOnOneLineOrOnePerLine: true -ConstructorInitializerIndentWidth: 2 -ContinuationIndentWidth: 2 -Cpp11BracedListStyle: true -FixNamespaceComments: true +ColumnLimit: '80' +ConstructorInitializerAllOnOneLineOrOnePerLine: 'true' +ConstructorInitializerIndentWidth: '2' +ContinuationIndentWidth: '2' +Cpp11BracedListStyle: 'true' +FixNamespaceComments: 'true' IncludeBlocks: Preserve -IndentCaseLabels: true +IndentCaseLabels: 'true' IndentPPDirectives: AfterHash -IndentWidth: 2 -IndentWrappedFunctionNames: false -KeepEmptyLinesAtTheStartOfBlocks: false +IndentWidth: '2' +KeepEmptyLinesAtTheStartOfBlocks: 'false' Language: Cpp -MacroBlockBegin: "^BEGIN_STATE$|CAF_BEGIN_TYPE_ID_BLOCK" -MacroBlockEnd: "^END_STATE$|CAF_END_TYPE_ID_BLOCK" -MaxEmptyLinesToKeep: 1 +MacroBlockBegin: ^BEGIN_STATE$|CAF_BEGIN_TYPE_ID_BLOCK +MacroBlockEnd: ^END_STATE$|CAF_END_TYPE_ID_BLOCK +MaxEmptyLinesToKeep: '1' NamespaceIndentation: None -PenaltyBreakAssignment: 25 -PenaltyBreakBeforeFirstCallParameter: 50 -PenaltyReturnTypeOnItsOwnLine: 25 +PenaltyBreakAssignment: '21' +PenaltyBreakBeforeFirstCallParameter: '60' +PenaltyReturnTypeOnItsOwnLine: '50' PointerAlignment: Left -ReflowComments: true -SortIncludes: true -SortUsingDeclarations: true -SpaceAfterCStyleCast: true -SpaceAfterTemplateKeyword: true -SpaceBeforeAssignmentOperators: true -SpaceBeforeCpp11BracedList: false -SpaceBeforeCtorInitializerColon: true -SpaceBeforeInheritanceColon: true +SpaceAfterCStyleCast: 'true' SpaceBeforeParens: ControlStatements -SpaceBeforeRangeBasedForLoopColon: true -SpaceInEmptyParentheses: false -SpacesBeforeTrailingComments: 1 -SpacesInAngles: false -SpacesInContainerLiterals: false -SpacesInParentheses: false -SpacesInSquareBrackets: false +SpacesBeforeTrailingComments: '1' Standard: Cpp11 UseTab: Never + ... diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml new file mode 100644 index 00000000..3e9e012b --- /dev/null +++ b/.github/workflows/pre-commit.yml @@ -0,0 +1,14 @@ +name: pre-commit + +on: + pull_request: + push: + branches: [master] + +jobs: + pre-commit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + - uses: pre-commit/action@v3.0.0 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..e04646fb --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,9 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +# +repos: +- repo: https://github.com/pre-commit/mirrors-clang-format + rev: 'v13.0.0' + hooks: + - id: clang-format + exclude: ^tests/benchmark/readerwriterqueue/ diff --git a/bindings/python/_broker.cpp b/bindings/python/_broker.cpp index 72c586f9..7bcdec25 100644 --- a/bindings/python/_broker.cpp +++ b/bindings/python/_broker.cpp @@ -7,15 +7,15 @@ #include #ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wpedantic" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wpedantic" #endif #include #include #include #include #ifdef __GNUC__ -#pragma GCC diagnostic pop +# pragma GCC diagnostic pop #endif #include "broker/backend.hh" @@ -78,7 +78,7 @@ namespace { broker::endpoint_id node_from_str(const std::string& node_str) { broker::endpoint_id node; - if(!broker::convert(node_str,node)) + if (!broker::convert(node_str, node)) throw std::invalid_argument( "endpoint::await_peer called with invalid endpoint ID"); return node; @@ -96,42 +96,48 @@ PYBIND11_MODULE(_broker, m) { init_store(m); auto version = m.def_submodule("Version", "Version constants"); - version.attr("MAJOR") - = py::cast(new broker::version::type{broker::version::major}); - version.attr("MINOR") - = py::cast(new broker::version::type{broker::version::minor}); - version.attr("PATCH") - = py::cast(new broker::version::type{broker::version::patch}); - version.attr("PROTOCOL") - = py::cast(new broker::version::type{broker::version::protocol}); + version.attr("MAJOR") = + py::cast(new broker::version::type{broker::version::major}); + version.attr("MINOR") = + py::cast(new broker::version::type{broker::version::minor}); + version.attr("PATCH") = + py::cast(new broker::version::type{broker::version::patch}); + version.attr("PROTOCOL") = + py::cast(new broker::version::type{broker::version::protocol}); version.def("compatible", &broker::version::compatible, "Checks whether two Broker protocol versions are compatible"); m.def("now", &broker::now, "Get the current wallclock time"); py::class_(m, "EndpointInfo") - // TODO: Can we convert this optional directly into network_info or None? + // TODO: Can we convert this optional directly into + // network_info or None? .def_readwrite("network", &broker::endpoint_info::network) .def_readwrite("type", &broker::endpoint_info::type) - .def("node_id", [](const broker::endpoint_info& e) { return to_string(e.node); }) - .def("__repr__", [](const broker::endpoint_info& e) { return to_string(e.node); }); + .def("node_id", + [](const broker::endpoint_info& e) { return to_string(e.node); }) + .def("__repr__", + [](const broker::endpoint_info& e) { return to_string(e.node); }); py::class_(m, "NetworkInfo") .def_readwrite("address", &broker::network_info::address) .def_readwrite("port", &broker::network_info::port) - .def("__repr__", [](const broker::network_info& n) { return to_string(n); }); + .def("__repr__", + [](const broker::network_info& n) { return to_string(n); }); py::class_>(m, "OptionalNetworkInfo") .def("is_set", - [](std::optional& i) { return static_cast(i);}) - .def("get", - [](std::optional& i) { return *i; }) - .def("__repr__", [](const std::optional& i) -> std::string { - if (i) - return broker::to_string(*i); - else - return "nil"; - }); + [](std::optional& i) { + return static_cast(i); + }) + .def("get", [](std::optional& i) { return *i; }) + .def("__repr__", + [](const std::optional& i) -> std::string { + if (i) + return broker::to_string(*i); + else + return "nil"; + }); py::class_(m, "PeerInfo") .def_readwrite("peer", &broker::peer_info::peer) @@ -141,23 +147,21 @@ PYBIND11_MODULE(_broker, m) { py::bind_vector>(m, "VectorPeerInfo"); #ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wself-assign-overloaded" +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wself-assign-overloaded" #endif py::class_(m, "Topic") .def(py::init()) // Without the enclosing pragmas, this line raises a nonsensical self-assign // warning on Clang. See https://bugs.llvm.org/show_bug.cgi?id=43124. - .def(py::self /= py::self, - "Appends a topic component with a separator") - .def(py::self / py::self, - "Appends topic components with a separator") + .def(py::self /= py::self, "Appends a topic component with a separator") + .def(py::self / py::self, "Appends topic components with a separator") .def("string", &broker::topic::string, "Get the underlying string representation of the topic", py::return_value_policy::reference_internal) .def("__repr__", [](const broker::topic& t) { return t.string(); }); #ifdef __clang__ -#pragma clang diagnostic pop +# pragma clang diagnostic pop #endif py::bind_vector>(m, "VectorTopic"); @@ -169,82 +173,93 @@ PYBIND11_MODULE(_broker, m) { .def("capacity", &broker::publisher::capacity) .def("fd", &broker::publisher::fd) .def("drop_all_on_destruction", &broker::publisher::drop_all_on_destruction) - .def("publish", (void (broker::publisher::*)(broker::data d)) &broker::publisher::publish) - .def("publish_batch", - [](broker::publisher& p, std::vector xs) { p.publish(xs); }) + .def("publish", (void(broker::publisher::*)(broker::data d)) + & broker::publisher::publish) + .def("publish_batch", [](broker::publisher& p, + std::vector xs) { p.publish(xs); }) .def("reset", &broker::publisher::reset); using topic_data_pair = std::pair; py::bind_vector>(m, "VectorPairTopicData"); - py::class_>(m, "OptionalSubscriberBaseValueType") + py::class_>(m, + "OptionalSubscriberBaseValueType") .def("is_set", - [](std::optional& i) { return static_cast(i);}) - .def("get", - [](std::optional& i) { return *i; }) - .def("__repr__", [](const std::optional& i) { return custom_to_string(i); }); + [](std::optional& i) { return static_cast(i); }) + .def("get", [](std::optional& i) { return *i; }) + .def("__repr__", [](const std::optional& i) { + return custom_to_string(i); + }); py::class_(m, "Subscriber") .def("get", [](broker::subscriber& ep) -> topic_data_pair { - auto res = ep.get(); - return std::make_pair(broker::get_topic(res), broker::get_data(res)); - }) + auto res = ep.get(); + return std::make_pair(broker::get_topic(res), broker::get_data(res)); + }) .def("get", - [](broker::subscriber& ep, double secs) -> std::optional { - auto res = ep.get(broker::to_duration(secs)); - std::optional rval; - if (res) { - auto p = std::make_pair(broker::get_topic(*res), broker::get_data(*res)); - rval = std::optional(std::move(p)); - } - return rval; - }) + [](broker::subscriber& ep, + double secs) -> std::optional { + auto res = ep.get(broker::to_duration(secs)); + std::optional rval; + if (res) { + auto p = std::make_pair(broker::get_topic(*res), + broker::get_data(*res)); + rval = std::optional(std::move(p)); + } + return rval; + }) .def("get", - [](broker::subscriber& ep, size_t num) -> std::vector { - auto res = ep.get(num); - std::vector rval; - rval.reserve(res.size()); - for ( auto& e : res ) - rval.emplace_back(std::make_pair(broker::get_topic(e), broker::get_data(e))); - return rval; - }) + [](broker::subscriber& ep, + size_t num) -> std::vector { + auto res = ep.get(num); + std::vector rval; + rval.reserve(res.size()); + for (auto& e : res) + rval.emplace_back( + std::make_pair(broker::get_topic(e), broker::get_data(e))); + return rval; + }) .def("get", - [](broker::subscriber& ep, size_t num, double secs) -> std::vector { - auto res = ep.get(num, broker::to_duration(secs)); - std::vector rval; - rval.reserve(res.size()); - for ( auto& e : res ) - rval.emplace_back(std::make_pair(broker::get_topic(e), broker::get_data(e))); - return rval; - }) + [](broker::subscriber& ep, size_t num, + double secs) -> std::vector { + auto res = ep.get(num, broker::to_duration(secs)); + std::vector rval; + rval.reserve(res.size()); + for (auto& e : res) + rval.emplace_back( + std::make_pair(broker::get_topic(e), broker::get_data(e))); + return rval; + }) .def("poll", [](broker::subscriber& ep) -> std::vector { - auto res = ep.poll(); - std::vector rval; - rval.reserve(res.size()); - for ( auto& e : res ) - rval.emplace_back(std::make_pair(broker::get_topic(e), broker::get_data(e))); - return rval; - }) + auto res = ep.poll(); + std::vector rval; + rval.reserve(res.size()); + for (auto& e : res) + rval.emplace_back( + std::make_pair(broker::get_topic(e), broker::get_data(e))); + return rval; + }) .def("available", &broker::subscriber::available) .def("fd", &broker::subscriber::fd) .def("add_topic", &broker::subscriber::add_topic) .def("remove_topic", &broker::subscriber::remove_topic) .def("reset", &broker::subscriber::reset); - py::bind_vector>(m, "VectorStatusSubscriberValueType"); + py::bind_vector>( + m, "VectorStatusSubscriberValueType"); py::class_(m, "Status") .def(py::init<>()) .def("code", &broker::status::code) .def("context", &broker::status::context, - py::return_value_policy::reference_internal) + py::return_value_policy::reference_internal) .def("__repr__", [](const broker::status& s) { return to_string(s); }); py::class_(m, "Error") @@ -252,42 +267,64 @@ PYBIND11_MODULE(_broker, m) { .def("code", &broker::error::code) .def("__repr__", [](const broker::error& e) { return to_string(e); }); - py::class_ status_subscriber(m, "StatusSubscriber"); + py::class_ status_subscriber(m, + "StatusSubscriber"); status_subscriber - .def("get", (broker::status_subscriber::value_type (broker::status_subscriber::*)()) &broker::status_subscriber::get) .def("get", - [](broker::status_subscriber& ep, double secs) -> std::optional { - return ep.get(broker::to_duration(secs)); }) + (broker::status_subscriber::value_type(broker::status_subscriber::*)()) + & broker::status_subscriber::get) .def("get", - [](broker::status_subscriber& ep, size_t num) -> std::vector { - return ep.get(num); }) + [](broker::status_subscriber& ep, double secs) + -> std::optional { + return ep.get(broker::to_duration(secs)); + }) .def("get", - [](broker::status_subscriber& ep, size_t num, double secs) -> std::vector { - return ep.get(num, broker::to_duration(secs)); }) + [](broker::status_subscriber& ep, + size_t num) -> std::vector { + return ep.get(num); + }) + .def("get", + [](broker::status_subscriber& ep, size_t num, + double secs) -> std::vector { + return ep.get(num, broker::to_duration(secs)); + }) .def("poll", - [](broker::status_subscriber& ep) -> std::vector { - return ep.poll(); }) + [](broker::status_subscriber& ep) + -> std::vector { + return ep.poll(); + }) .def("available", &broker::status_subscriber::available) .def("fd", &broker::status_subscriber::fd) .def("reset", &broker::status_subscriber::reset); - py::class_(status_subscriber, "ValueType") + py::class_(status_subscriber, + "ValueType") .def("is_error", - [](broker::status_subscriber::value_type& x) -> bool { return std::holds_alternative(x);}) + [](broker::status_subscriber::value_type& x) -> bool { + return std::holds_alternative(x); + }) .def("is_status", - [](broker::status_subscriber::value_type& x) -> bool { return std::holds_alternative(x);}) + [](broker::status_subscriber::value_type& x) -> bool { + return std::holds_alternative(x); + }) .def("get_error", - [](broker::status_subscriber::value_type& x) -> broker::error { return std::get(x);}) + [](broker::status_subscriber::value_type& x) -> broker::error { + return std::get(x); + }) .def("get_status", - [](broker::status_subscriber::value_type& x) -> broker::status { return std::get(x);}); + [](broker::status_subscriber::value_type& x) -> broker::status { + return std::get(x); + }); py::bind_map(m, "MapBackendOptions"); py::class_(m, "BrokerOptions") .def(py::init<>()) .def_readwrite("disable_ssl", &broker::broker_options::disable_ssl) - .def_readwrite("disable_forwarding", &broker::broker_options::disable_forwarding) - .def_readwrite("ignore_broker_conf", &broker::broker_options::ignore_broker_conf) + .def_readwrite("disable_forwarding", + &broker::broker_options::disable_forwarding) + .def_readwrite("ignore_broker_conf", + &broker::broker_options::ignore_broker_conf) .def_readwrite("use_real_time", &broker::broker_options::use_real_time); // We need a configuration class here that's separate from @@ -295,7 +332,7 @@ PYBIND11_MODULE(_broker, m) { // the standard class right at that point, one cannot pass an already // created one in, which is unfortunate. struct Configuration { - Configuration() {}; + Configuration(){}; Configuration(broker::broker_options opts) : options(std::move(opts)) {} broker::broker_options options = {}; std::string openssl_cafile; @@ -319,72 +356,80 @@ PYBIND11_MODULE(_broker, m) { py::class_(m, "Endpoint") .def(py::init<>()) .def(py::init([](Configuration cfg) { - broker::configuration bcfg(cfg.options); - bcfg.openssl_capath(cfg.openssl_capath); - bcfg.openssl_passphrase (cfg.openssl_passphrase); - bcfg.openssl_cafile(cfg.openssl_cafile); - bcfg.openssl_certificate(cfg.openssl_certificate); - bcfg.openssl_key(cfg.openssl_key); - if ( cfg.max_threads > 0 ) - bcfg.set("caf.scheduler.max-threads", static_cast(cfg.max_threads)); - return std::unique_ptr(new broker::endpoint(std::move(bcfg))); - })) - .def("__repr__", [](const broker::endpoint& e) { return to_string(e.node_id()); }) - .def("node_id", [](const broker::endpoint& e) { return to_string(e.node_id()); }) - .def("listen", - [](broker::endpoint&ep,std::string& addr, uint16_t port) { - return ep.listen(addr, port); - }) - .def("peer", - [](broker::endpoint& ep, std::string& addr, uint16_t port, double retry) -> bool { - return ep.peer(addr, port, std::chrono::seconds((int)retry));}, - py::arg("addr"), py::arg("port"), py::arg("retry") = 10.0 - ) - .def("peer_nosync", - [](broker::endpoint& ep, std::string& addr, uint16_t port, double retry) { - ep.peer_nosync(addr, port, std::chrono::seconds((int)retry));}, - py::arg("addr"), py::arg("port"), py::arg("retry") = 10.0 - ) + broker::configuration bcfg(cfg.options); + bcfg.openssl_capath(cfg.openssl_capath); + bcfg.openssl_passphrase(cfg.openssl_passphrase); + bcfg.openssl_cafile(cfg.openssl_cafile); + bcfg.openssl_certificate(cfg.openssl_certificate); + bcfg.openssl_key(cfg.openssl_key); + if (cfg.max_threads > 0) + bcfg.set("caf.scheduler.max-threads", + static_cast(cfg.max_threads)); + return std::unique_ptr( + new broker::endpoint(std::move(bcfg))); + })) + .def("__repr__", + [](const broker::endpoint& e) { return to_string(e.node_id()); }) + .def("node_id", + [](const broker::endpoint& e) { return to_string(e.node_id()); }) + .def("listen", [](broker::endpoint& ep, std::string& addr, + uint16_t port) { return ep.listen(addr, port); }) + .def( + "peer", + [](broker::endpoint& ep, std::string& addr, uint16_t port, + double retry) -> bool { + return ep.peer(addr, port, std::chrono::seconds((int) retry)); + }, + py::arg("addr"), py::arg("port"), py::arg("retry") = 10.0) + .def( + "peer_nosync", + [](broker::endpoint& ep, std::string& addr, uint16_t port, double retry) { + ep.peer_nosync(addr, port, std::chrono::seconds((int) retry)); + }, + py::arg("addr"), py::arg("port"), py::arg("retry") = 10.0) .def("unpeer", &broker::endpoint::unpeer) .def("unpeer_nosync", &broker::endpoint::unpeer_nosync) .def("peers", &broker::endpoint::peers) .def("peer_subscriptions", &broker::endpoint::peer_subscriptions) .def("forward", &broker::endpoint::forward) - .def("publish", (void (broker::endpoint::*)(broker::topic t, broker::data d)) &broker::endpoint::publish) - .def("publish", (void (broker::endpoint::*)(const broker::endpoint_info& dst, broker::topic t, broker::data d)) &broker::endpoint::publish) + .def("publish", (void(broker::endpoint::*)(broker::topic t, broker::data d)) + & broker::endpoint::publish) + .def("publish", (void(broker::endpoint::*)(const broker::endpoint_info& dst, + broker::topic t, broker::data d)) + & broker::endpoint::publish) .def("publish_batch", - [](broker::endpoint& ep, std::vector batch) { - std::vector xs; - xs.reserve(batch.size()); - for ( auto& m : batch ) - xs.emplace_back(std::move(m.first), std::move(m.second)); - ep.publish(std::move(xs)); - }) + [](broker::endpoint& ep, std::vector batch) { + std::vector xs; + xs.reserve(batch.size()); + for (auto& m : batch) + xs.emplace_back(std::move(m.first), std::move(m.second)); + ep.publish(std::move(xs)); + }) .def("make_publisher", &broker::endpoint::make_publisher) - .def("make_subscriber", &broker::endpoint::make_subscriber, py::arg("topics"), py::arg("max_qsize") = 20) - .def("make_status_subscriber", - [](broker::endpoint& ep, bool receive_statuses) { - return ep.make_status_subscriber(receive_statuses); - }, - py::arg("receive_statuses") = false) + .def("make_subscriber", &broker::endpoint::make_subscriber, + py::arg("topics"), py::arg("max_qsize") = 20) + .def( + "make_status_subscriber", + [](broker::endpoint& ep, bool receive_statuses) { + return ep.make_status_subscriber(receive_statuses); + }, + py::arg("receive_statuses") = false) .def("shutdown", &broker::endpoint::shutdown) .def("attach_master", [](broker::endpoint& ep, const std::string& name, broker::backend type, - const broker::backend_options& opts) -> broker::expected { - return ep.attach_master(name, type, opts); - }) + const broker::backend_options& opts) + -> broker::expected { + return ep.attach_master(name, type, opts); + }) .def("attach_clone", - [](broker::endpoint& ep, const std::string& name) -> broker::expected { - return ep.attach_clone(name); - }) + [](broker::endpoint& ep, const std::string& name) + -> broker::expected { return ep.attach_clone(name); }) .def("await_peer", [](broker::endpoint& ep, const std::string& node_str) { return ep.await_peer(node_from_str(node_str)); }) - .def("await_peer", - [](broker::endpoint& ep, const std::string& node_str, broker::timespan timeout) { - return ep.await_peer(node_from_str(node_str), timeout); - }) - ; + .def("await_peer", [](broker::endpoint& ep, const std::string& node_str, + broker::timespan timeout) { + return ep.await_peer(node_from_str(node_str), timeout); + }); } - diff --git a/bindings/python/data.cpp b/bindings/python/data.cpp index 6e1f6180..1854c02c 100644 --- a/bindings/python/data.cpp +++ b/bindings/python/data.cpp @@ -1,21 +1,21 @@ +#include #include #include -#include #ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wpedantic" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wpedantic" #endif #include #ifdef __GNUC__ -#pragma GCC diagnostic pop +# pragma GCC diagnostic pop #endif #include "set_bind.h" -#include "broker/data.hh" #include "broker/convert.hh" +#include "broker/data.hh" #include "broker/detail/assert.hh" #include "broker/detail/operators.hh" @@ -26,12 +26,24 @@ using namespace pybind11::literals; // unsigned integers. struct count_type { count_type(broker::count c) : value{c} {} - bool operator==(const count_type& other) const { return value == other.value; } - bool operator!=(const count_type& other) const { return value != other.value; } - bool operator<(const count_type& other) const { return value < other.value; } - bool operator<=(const count_type& other) const { return value <= other.value; } - bool operator>(const count_type& other) const { return value > other.value; } - bool operator>=(const count_type& other) const { return value >= other.value; } + bool operator==(const count_type& other) const { + return value == other.value; + } + bool operator!=(const count_type& other) const { + return value != other.value; + } + bool operator<(const count_type& other) const { + return value < other.value; + } + bool operator<=(const count_type& other) const { + return value <= other.value; + } + bool operator>(const count_type& other) const { + return value > other.value; + } + bool operator>=(const count_type& other) const { + return value >= other.value; + } broker::count value; }; @@ -42,26 +54,27 @@ struct hash { return std::hash{}(v.value); } }; -} +} // namespace std void init_data(py::module& m) { - py::class_ address_type{m, "Address"}; address_type.def(py::init<>()) .def(py::init([](const py::bytes& bytes, int family) { - BROKER_ASSERT(family == 4 || family == 6); - auto str = static_cast(bytes); - auto ptr = reinterpret_cast(str.data()); - auto f = family == 4 ? broker::address::family::ipv4 : - broker::address::family::ipv6; - return broker::address{ptr, f, broker::address::byte_order::network}; - })) + BROKER_ASSERT(family == 4 || family == 6); + auto str = static_cast(bytes); + auto ptr = reinterpret_cast(str.data()); + auto f = family == 4 ? broker::address::family::ipv4 + : broker::address::family::ipv6; + return broker::address{ptr, f, broker::address::byte_order::network}; + })) .def("mask", &broker::address::mask, "top_bits_to_keep"_a) .def("is_v4", &broker::address::is_v4) .def("is_v6", &broker::address::is_v6) - .def("bytes", [](const broker::address& a) { - return py::bytes(std::string(std::begin(a.bytes()), std::end(a.bytes()))); - }) + .def("bytes", + [](const broker::address& a) { + return py::bytes( + std::string(std::begin(a.bytes()), std::end(a.bytes()))); + }) .def("__repr__", [](const broker::address& a) { return broker::to_string(a); }) .def(hash(py::self)) @@ -84,7 +97,10 @@ void init_data(py::module& m) { .def(py::init()) .def_readwrite("value", &count_type::value) .def("__str__", [](const count_type& c) { return std::to_string(c.value); }) - .def("__repr__", [](const count_type& c) { return "Count(" + std::to_string(c.value) + ")"; }) + .def("__repr__", + [](const count_type& c) { + return "Count(" + std::to_string(c.value) + ")"; + }) .def(hash(py::self)) .def(py::self < py::self) .def(py::self <= py::self) @@ -96,7 +112,8 @@ void init_data(py::module& m) { py::class_{m, "Enum"} .def(py::init()) .def_readwrite("name", &broker::enum_value::name) - .def("__repr__", [](const broker::enum_value& e) { return broker::to_string(e); }) + .def("__repr__", + [](const broker::enum_value& e) { return broker::to_string(e); }) .def(hash(py::self)) .def(py::self < py::self) .def(py::self <= py::self) @@ -106,8 +123,7 @@ void init_data(py::module& m) { .def(py::self != py::self); py::class_ port_type{m, "Port"}; - port_type - .def(py::init<>()) + port_type.def(py::init<>()) .def(py::init()) .def("number", &broker::port::number) .def("get_type", &broker::port::type) @@ -134,8 +150,8 @@ void init_data(py::module& m) { py::class_(m, "Subnet") .def(py::init<>()) .def(py::init([](broker::address addr, uint8_t length) { - return broker::subnet(std::move(addr), length); - })) + return broker::subnet(std::move(addr), length); + })) .def("contains", &broker::subnet::contains, "addr"_a) .def("network", &broker::subnet::network) .def("length", &broker::subnet::length) @@ -151,11 +167,10 @@ void init_data(py::module& m) { py::class_(m, "Timespan") .def(py::init<>()) .def(py::init()) - .def(py::init([](double secs) { - return broker::to_timespan(secs); - })) + .def(py::init([](double secs) { return broker::to_timespan(secs); })) .def("count", &broker::timespan::count) - .def("__repr__", [](const broker::timespan& s) { return broker::to_string(s); }) + .def("__repr__", + [](const broker::timespan& s) { return broker::to_string(s); }) .def(hash(py::self)) .def(py::self + py::self) .def(py::self - py::self) @@ -175,11 +190,10 @@ void init_data(py::module& m) { py::class_(m, "Timestamp") .def(py::init<>()) .def(py::init()) - .def(py::init([](double secs) { - return broker::to_timestamp(secs); - })) + .def(py::init([](double secs) { return broker::to_timestamp(secs); })) .def("time_since_epoch", &broker::timestamp::time_since_epoch) - .def("__repr__", [](const broker::timestamp& ts) { return broker::to_string(ts); }) + .def("__repr__", + [](const broker::timestamp& ts) { return broker::to_string(ts); }) .def(hash(py::self)) .def(py::self < py::self) .def(py::self <= py::self) @@ -191,17 +205,12 @@ void init_data(py::module& m) { py::bind_vector(m, "Vector"); py::class_ data_type{m, "Data"}; - data_type - .def(py::init<>()) + data_type.def(py::init<>()) .def(py::init()) .def(py::init()) .def(py::init()) - .def(py::init([](count_type c) { - return broker::data{c.value}; - })) - .def(py::init([](broker::enum_value e) { - return broker::data{e}; - })) + .def(py::init([](count_type c) { return broker::data{c.value}; })) + .def(py::init([](broker::enum_value e) { return broker::data{e}; })) .def(py::init()) .def(py::init()) .def(py::init()) @@ -212,29 +221,48 @@ void init_data(py::module& m) { .def(py::init()) .def(py::init()) .def(py::init()) - .def("as_address", [](const broker::data& d) { return broker::get(d); }) - .def("as_boolean", [](const broker::data& d) { return broker::get(d); }) - .def("as_count", [](const broker::data& d) { return broker::get(d); }) - .def("as_enum_value", [](const broker::data& d) { return broker::get(d); }) - .def("as_integer", [](const broker::data& d) { return broker::get(d); }) - .def("as_none", [](const broker::data& d) { return broker::get(d); }) - .def("as_port", [](const broker::data& d) { return broker::get(d); }) - .def("as_real", [](const broker::data& d) { return broker::get(d); }) - .def("as_set", [](const broker::data& d) { return broker::get(d); }) - .def("as_string", [](const broker::data& d) { return py::bytes(broker::get(d)); }) - .def("as_subnet", [](const broker::data& d) { return broker::get(d); }) - .def("as_table", [](const broker::data& d) { return broker::get(d); }) - .def("as_timespan", [](const broker::data& d) { - double s; - broker::convert(broker::get(d), s); - return s; - }) - .def("as_timestamp", [](const broker::data& d) { - double s; - broker::convert(broker::get(d), s); - return s; - }) - .def("as_vector", [](const broker::data& d) { return broker::get(d); }) + .def("as_address", + [](const broker::data& d) { return broker::get(d); }) + .def("as_boolean", + [](const broker::data& d) { return broker::get(d); }) + .def("as_count", + [](const broker::data& d) { return broker::get(d); }) + .def("as_enum_value", + [](const broker::data& d) { + return broker::get(d); + }) + .def("as_integer", + [](const broker::data& d) { return broker::get(d); }) + .def("as_none", + [](const broker::data& d) { return broker::get(d); }) + .def("as_port", + [](const broker::data& d) { return broker::get(d); }) + .def("as_real", + [](const broker::data& d) { return broker::get(d); }) + .def("as_set", + [](const broker::data& d) { return broker::get(d); }) + .def("as_string", + [](const broker::data& d) { + return py::bytes(broker::get(d)); + }) + .def("as_subnet", + [](const broker::data& d) { return broker::get(d); }) + .def("as_table", + [](const broker::data& d) { return broker::get(d); }) + .def("as_timespan", + [](const broker::data& d) { + double s; + broker::convert(broker::get(d), s); + return s; + }) + .def("as_timestamp", + [](const broker::data& d) { + double s; + broker::convert(broker::get(d), s); + return s; + }) + .def("as_vector", + [](const broker::data& d) { return broker::get(d); }) .def("get_type", &broker::data::get_type) .def("__str__", [](const broker::data& d) { return broker::to_string(d); }) .def(hash(py::self)) @@ -263,4 +291,3 @@ void init_data(py::module& m) { .value("Timestamp", broker::data::type::timestamp) .value("Vector", broker::data::type::vector); } - diff --git a/bindings/python/enums.cpp b/bindings/python/enums.cpp index 2597a886..7d19542f 100644 --- a/bindings/python/enums.cpp +++ b/bindings/python/enums.cpp @@ -2,12 +2,12 @@ #include #ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wpedantic" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wpedantic" #endif #include #ifdef __GNUC__ -#pragma GCC diagnostic pop +# pragma GCC diagnostic pop #endif #include "broker/api_flags.hh" diff --git a/bindings/python/set_bind.h b/bindings/python/set_bind.h index f79c2edc..8eab03ec 100644 --- a/bindings/python/set_bind.h +++ b/bindings/python/set_bind.h @@ -1,5 +1,6 @@ // -// Augment pybind11's {map,vector}_bind() with set_bind() for mapping std::set to Python's sets. +// Augment pybind11's {map,vector}_bind() with set_bind() for mapping std::set +// to Python's sets. // // This code is copied and adapted from pybind11's version for vector. // @@ -9,102 +10,101 @@ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) PYBIND11_NAMESPACE_BEGIN(detail) -/* For a set data structure, recursively check the value type (which is std::pair for maps) */ +/* For a set data structure, recursively check the value type (which is + * std::pair for maps) */ template struct is_comparable::is_set>> { - static constexpr const bool value = - is_comparable::value; + static constexpr const bool value = + is_comparable::value; }; /* Fallback functions */ -template void set_if_copy_constructible(const Args &...) { } -template void set_if_equal_operator(const Args &...) { } -template void set_if_insertion_operator(const Args &...) { } -template void set_modifiers(const Args &...) { } +template +void set_if_copy_constructible(const Args&...) {} +template +void set_if_equal_operator(const Args&...) {} +template +void set_if_insertion_operator(const Args&...) {} +template +void set_modifiers(const Args&...) {} -template -void set_if_copy_constructible(enable_if_t< - std::is_copy_constructible::value && - std::is_copy_constructible::value, Class_> &cl) { - - cl.def(init(), "Copy constructor"); +template +void set_if_copy_constructible( + enable_if_t::value + && std::is_copy_constructible::value, + Class_>& cl) { + cl.def(init(), "Copy constructor"); } -template -void set_if_equal_operator(enable_if_t::value, Class_> &cl) { - cl.def(self == self); - cl.def(self != self); +template +void set_if_equal_operator(enable_if_t::value, Class_>& cl) { + cl.def(self == self); + cl.def(self != self); } // Set modifiers -- requires a copyable set_type: template -void set_modifiers(enable_if_t::value, Class_> &cl) { - using T = typename Set::value_type; - - cl.def(init([](iterable it) { - Set rval; - for (handle h : it) - rval.insert(h.cast()); - return rval; - })); - - cl.def("add", - [](Set &s, const T &x) { - s.insert(x); - }, - arg("x"), - "Insert an item into this set." - ); - - cl.def("remove", - [](Set &s, const T &x) { - s.erase(x); - }, - arg("x"), - "Removes an item from this set." - ); - - cl.def("clear", - [](Set &s) { - s.clear(); - }, - "Empties this set." - ); +void set_modifiers( + enable_if_t::value, + Class_>& cl) { + using T = typename Set::value_type; + + cl.def(init([](iterable it) { + Set rval; + for (handle h : it) + rval.insert(h.cast()); + return rval; + })); + + cl.def( + "add", [](Set& s, const T& x) { s.insert(x); }, arg("x"), + "Insert an item into this set."); + + cl.def( + "remove", [](Set& s, const T& x) { s.erase(x); }, arg("x"), + "Removes an item from this set."); + + cl.def( + "clear", [](Set& s) { s.clear(); }, "Empties this set."); } // To iterate by copying objects, as std::set iterators are const. template -void set_accessor(Class_ &cl) { - using T = typename Set::value_type; - using ItType = typename Set::iterator; - - cl.def("__iter__", - [](Set &s) { - return make_iterator< - return_value_policy::copy, ItType, ItType, T>( - s.begin(), s.end()); - }, - keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */ - ); +void set_accessor(Class_& cl) { + using T = typename Set::value_type; + using ItType = typename Set::iterator; + + cl.def( + "__iter__", + [](Set& s) { + return make_iterator( + s.begin(), s.end()); + }, + keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */ + ); } -template auto set_if_insertion_operator(Class_ &cl, std::string const &name) - -> decltype(std::declval() << std::declval(), void()) { - cl.def("__repr__", - [name](Set& s) { - std::ostringstream t; - bool first = true; - t << name << "{"; - for (auto i : s) { - if (! first) - t << ", "; - t << i; - first = false; - } - t << '}'; - return t.str(); - }, - "Return the canonical string representation of this set."); +template +auto set_if_insertion_operator(Class_& cl, std::string const& name) + -> decltype(std::declval() + << std::declval(), + void()) { + cl.def( + "__repr__", + [name](Set& s) { + std::ostringstream t; + bool first = true; + t << name << "{"; + for (auto i : s) { + if (!first) + t << ", "; + t << i; + first = false; + } + t << '}'; + return t.str(); + }, + "Return the canonical string representation of this set."); } PYBIND11_NAMESPACE_END(detail) @@ -112,39 +112,39 @@ PYBIND11_NAMESPACE_END(detail) // // std::set // -template , typename... Args> -class_ bind_set(module &m, std::string const &name, Args&&... args) { - using Class_ = class_; +template , + typename... Args> +class_ bind_set(module& m, std::string const& name, + Args&&... args) { + using Class_ = class_; - Class_ cl(m, name.c_str(), std::forward(args)...); + Class_ cl(m, name.c_str(), std::forward(args)...); - cl.def(init<>()); + cl.def(init<>()); - // Register copy constructor (if possible) - detail::set_if_copy_constructible(cl); + // Register copy constructor (if possible) + detail::set_if_copy_constructible(cl); - // Register comparison-related operators and functions (if possible) - detail::set_if_equal_operator(cl); + // Register comparison-related operators and functions (if possible) + detail::set_if_equal_operator(cl); - // Register stream insertion operator (if possible) - detail::set_if_insertion_operator(cl, name); + // Register stream insertion operator (if possible) + detail::set_if_insertion_operator(cl, name); - // Modifiers require copyable set value type - detail::set_modifiers(cl); + // Modifiers require copyable set value type + detail::set_modifiers(cl); - // Accessor and iterator; return by value if copyable, otherwise we return by ref + keep-alive - detail::set_accessor(cl); + // Accessor and iterator; return by value if copyable, otherwise we return by + // ref + keep-alive + detail::set_accessor(cl); - cl.def("__bool__", - [](const Set &s) -> bool { - return !s.empty(); - }, - "Check whether the set is nonempty" - ); + cl.def( + "__bool__", [](const Set& s) -> bool { return !s.empty(); }, + "Check whether the set is nonempty"); - cl.def("__len__", &Set::size); + cl.def("__len__", &Set::size); - return cl; + return cl; } PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/bindings/python/store.cpp b/bindings/python/store.cpp index 44a8565c..3ce0c795 100644 --- a/bindings/python/store.cpp +++ b/bindings/python/store.cpp @@ -1,14 +1,14 @@ -#include #include +#include #ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wpedantic" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wpedantic" #endif #include #ifdef __GNUC__ -#pragma GCC diagnostic pop +# pragma GCC diagnostic pop #endif #include "broker/data.hh" @@ -18,32 +18,39 @@ namespace py = pybind11; using namespace pybind11::literals; void init_store(py::module& m) { - py::class_>(m, "OptionalTimespan") .def(py::init<>()) - .def(py::init() - ); + .def(py::init()); py::class_>(m, "ExpectedStore") .def("is_valid", - [](broker::expected& e) -> bool { return static_cast(e);}) - .def("get", - [](broker::expected& e) -> broker::store& { return *e; }) - ; + [](broker::expected& e) -> bool { + return static_cast(e); + }) + .def("get", [](broker::expected& e) -> broker::store& { + return *e; + }); py::class_>(m, "ExpectedData") .def("is_valid", - [](broker::expected& e) -> bool { return static_cast(e);}) + [](broker::expected& e) -> bool { + return static_cast(e); + }) .def("get", - [](broker::expected& e) -> broker::data& { return *e; }) - ; + [](broker::expected& e) -> broker::data& { return *e; }); py::class_ store(m, "Store"); - store - .def("name", &broker::store::name) - .def("exists", (broker::expected (broker::store::*)(broker::data d) const) &broker::store::exists) - .def("get", (broker::expected (broker::store::*)(broker::data d) const) &broker::store::get) - .def("get_index_from_value", (broker::expected (broker::store::*)(broker::data d, broker::data index) const) &broker::store::get_index_from_value) + store.def("name", &broker::store::name) + .def("exists", (broker::expected(broker::store::*)( + broker::data d) const) + & broker::store::exists) + .def("get", (broker::expected(broker::store::*)( + broker::data d) const) + & broker::store::get) + .def("get_index_from_value", + (broker::expected( + broker::store::*)(broker::data d, broker::data index) const) + & broker::store::get_index_from_value) .def("keys", &broker::store::keys) .def("put", &broker::store::put) .def("put_unique", &broker::store::put_unique) @@ -52,20 +59,26 @@ void init_store(py::module& m) { .def("increment", &broker::store::increment) .def("decrement", &broker::store::decrement) .def("append", &broker::store::append) - .def("insert_into", (void (broker::store::*)(broker::data, broker::data, std::optional)) &broker::store::insert_into) - .def("insert_into", (void (broker::store::*)(broker::data, broker::data, broker::data, std::optional)) &broker::store::insert_into) + .def("insert_into", + (void(broker::store::*)(broker::data, broker::data, + std::optional)) + & broker::store::insert_into) + .def("insert_into", + (void(broker::store::*)(broker::data, broker::data, broker::data, + std::optional)) + & broker::store::insert_into) .def("remove_from", &broker::store::remove_from) .def("push", &broker::store::push) .def("pop", &broker::store::pop) .def("await_idle", [](broker::store& st) { return st.await_idle(); }) - .def("await_idle", [](broker::store& st, broker::timespan timeout) { return st.await_idle(timeout); }) + .def("await_idle", + [](broker::store& st, broker::timespan timeout) { + return st.await_idle(timeout); + }) .def("reset", &broker::store::reset); -// Don't need. -// py::class_(store, "Response") -// .def_readwrite("answer", &broker::store::response::answer) -// .def_readwrite("id", &broker::store::response::id); - + // Don't need. + // py::class_(store, "Response") + // .def_readwrite("answer", &broker::store::response::answer) + // .def_readwrite("id", &broker::store::response::id); } - - diff --git a/bindings/python/zeek.cpp b/bindings/python/zeek.cpp index 9d3c350c..4f2433ef 100644 --- a/bindings/python/zeek.cpp +++ b/bindings/python/zeek.cpp @@ -1,19 +1,19 @@ -#include -#include #include +#include +#include #ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wpedantic" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wpedantic" #endif #include #ifdef __GNUC__ -#pragma GCC diagnostic pop +# pragma GCC diagnostic pop #endif -#include "broker/zeek.hh" #include "broker/data.hh" +#include "broker/zeek.hh" namespace py = pybind11; using namespace pybind11::literals; @@ -21,42 +21,42 @@ using namespace pybind11::literals; void init_zeek(py::module& m) { py::class_(m, "Message") .def("as_data", - static_cast - (&broker::zeek::Message::as_data)); + static_cast( + &broker::zeek::Message::as_data)); py::class_(m, "Event") - .def(py::init([](broker::data data) { - return broker::zeek::Event(std::move(data)); - })) + .def(py::init( + [](broker::data data) { return broker::zeek::Event(std::move(data)); })) .def(py::init([](std::string name, broker::data args) { - return broker::zeek::Event(std::move(name), std::move(broker::get(args))); - })) - .def("valid", [](const broker::zeek::Event& ev) -> bool { - auto t = broker::zeek::Message::type(ev.as_data()); - if ( t != broker::zeek::Message::Type::Event ) - return false; - return ev.valid(); + return broker::zeek::Event(std::move(name), + std::move(broker::get(args))); + })) + .def("valid", + [](const broker::zeek::Event& ev) -> bool { + auto t = broker::zeek::Message::type(ev.as_data()); + if (t != broker::zeek::Message::Type::Event) + return false; + return ev.valid(); }) - .def("name", [](const broker::zeek::Event& ev) -> const std::string& { - auto t = broker::zeek::Message::type(ev.as_data()); - if ( t != broker::zeek::Message::Type::Event ) { - throw std::invalid_argument("invalid Event data/type"); - } - if ( ! ev.valid() ) { - throw std::invalid_argument("invalid Event data"); - } - return ev.name(); + .def("name", + [](const broker::zeek::Event& ev) -> const std::string& { + auto t = broker::zeek::Message::type(ev.as_data()); + if (t != broker::zeek::Message::Type::Event) { + throw std::invalid_argument("invalid Event data/type"); + } + if (!ev.valid()) { + throw std::invalid_argument("invalid Event data"); + } + return ev.name(); }) .def("args", [](const broker::zeek::Event& ev) -> const broker::vector& { - auto t = broker::zeek::Message::type(ev.as_data()); - if ( t != broker::zeek::Message::Type::Event ) { - throw std::invalid_argument("invalid Event data/type"); - } - if ( ! ev.valid() ) { - throw std::invalid_argument("invalid Event data"); - } - return ev.args(); - }) - ; + auto t = broker::zeek::Message::type(ev.as_data()); + if (t != broker::zeek::Message::Type::Event) { + throw std::invalid_argument("invalid Event data/type"); + } + if (!ev.valid()) { + throw std::invalid_argument("invalid Event data"); + } + return ev.args(); + }); } - diff --git a/doc/_examples/comm.cc b/doc/_examples/comm.cc index 129f3a57..1021486d 100644 --- a/doc/_examples/comm.cc +++ b/doc/_examples/comm.cc @@ -1,113 +1,110 @@ +#include #include #include -#include using namespace broker; -int main(){} +int main() {} void f1() { - -// --get-start -endpoint ep; -auto sub = ep.make_subscriber({"/topic/test"}); -auto msg = sub.get(); -auto topic = get_topic(msg); -auto data_ = get_data(msg); -std::cout << "topic: " << topic << " data: " << data_ << std::endl; -// --get-end - -/// - -// --poll-start -if ( sub.available() ) + // --get-start + endpoint ep; + auto sub = ep.make_subscriber({"/topic/test"}); + auto msg = sub.get(); + auto topic = get_topic(msg); + auto data_ = get_data(msg); + std::cout << "topic: " << topic << " data: " << data_ << std::endl; + // --get-end + + /// + + // --poll-start + if (sub.available()) msg = sub.get(); // Won't block now. -for ( auto m : sub.poll() ) // Iterate over all available messages - std::cout << "topic: " << get_topic(m) << " data: " << get_data(m) << std::endl; -// --poll-end + for (auto m : sub.poll()) // Iterate over all available messages + std::cout << "topic: " << get_topic(m) << " data: " << get_data(m) + << std::endl; + // --poll-end -/// + /// -// --fd-start -auto fd = sub.fd(); -::pollfd p = {fd, POLLIN, 0}; -auto n = ::poll(&p, 1, -1); -if (n < 0) + // --fd-start + auto fd = sub.fd(); + ::pollfd p = {fd, POLLIN, 0}; + auto n = ::poll(&p, 1, -1); + if (n < 0) std::terminate(); // poll failed -if (n == 1 && p.revents & POLLIN) { + if (n == 1 && p.revents & POLLIN) { auto msg = sub.get(); // Won't block now. // ... - } -// --fd-end + } + // --fd-end -/// + /// -// --publish-start -ep.publish("/topic/test", "42"); // Message is a single number. -ep.publish("/topic/test", vector{1, 2, 3}); // Message is a vector of values. -// --publish-end + // --publish-start + ep.publish("/topic/test", "42"); // Message is a single number. + ep.publish("/topic/test", vector{1, 2, 3}); // Message is a vector of values. + // --publish-end -/// + /// -// --publisher-start -auto pub = ep.make_publisher("/topic/test"); -pub.publish("42"); // Message is a single number. -pub.publish(vector{1, 2, 3}); // Message is a vector. -// --publisher-end + // --publisher-start + auto pub = ep.make_publisher("/topic/test"); + pub.publish("42"); // Message is a single number. + pub.publish(vector{1, 2, 3}); // Message is a vector. + // --publisher-end -/// + /// -// --peering-start -// Open port and subscribe to 'foo' with all -// incoming peerings. -// Establish outgoing peering and subscribe to 'bar'. -endpoint ep1; -auto sub1 = ep1.make_subscriber({"/topic/test"}); -ep1.peer("127.0.0.1", 9999); + // --peering-start + // Open port and subscribe to 'foo' with all + // incoming peerings. + // Establish outgoing peering and subscribe to 'bar'. + endpoint ep1; + auto sub1 = ep1.make_subscriber({"/topic/test"}); + ep1.peer("127.0.0.1", 9999); -endpoint ep0; -auto sub0 = ep0.make_subscriber({"/topic/test"}); -ep0.listen("127.0.0.1", 9999); -// --peering-end + endpoint ep0; + auto sub0 = ep0.make_subscriber({"/topic/test"}); + ep0.listen("127.0.0.1", 9999); + // --peering-end -// --status-subscriber-err-start -auto ss = ep.make_status_subscriber(); + // --status-subscriber-err-start + auto ss = ep.make_status_subscriber(); -if ( ss.available() ) { + if (ss.available()) { auto ss_res = ss.get(); auto err = get(ss_res); // Won't block now. - std::cerr << "Broker error:" << err.code() << ", " << to_string(err) << std::endl; -} -// --status-subscriber-err-end + std::cerr << "Broker error:" << err.code() << ", " << to_string(err) + << std::endl; + } + // --status-subscriber-err-end } -void f2() -{ -endpoint ep; +void f2() { + endpoint ep; -// --status-subscriber-all-start -auto ss = ep.make_status_subscriber(true); // Get status updates and errors. + // --status-subscriber-all-start + auto ss = ep.make_status_subscriber(true); // Get status updates and errors. -if ( ss.available() ) { + if (ss.available()) { auto s = ss.get(); - if ( auto err = get_if(&s) ) - std::cerr << "Broker error:" << err->code() << ", " << to_string(*err) << std::endl; - - if ( auto st = get_if(&s) ) { - if ( auto ctx = st->context() ) // Get the peer this is about if available. - std::cerr << "Broker status update regarding " - << ctx->network->address - << ":" << to_string(*st) << std::endl; - else - std::cerr << "Broker status update:" - << to_string(*st) << std::endl; + if (auto err = get_if(&s)) + std::cerr << "Broker error:" << err->code() << ", " << to_string(*err) + << std::endl; + + if (auto st = get_if(&s)) { + if (auto ctx = st->context()) // Get the peer this is about + // if available. + std::cerr << "Broker status update regarding " << ctx->network->address + << ":" << to_string(*st) << std::endl; + else + std::cerr << "Broker status update:" << to_string(*st) << std::endl; } -// --status-subscriber-all-end -} - + // --status-subscriber-all-end + } } - - diff --git a/doc/_examples/ping.cc b/doc/_examples/ping.cc index 11c14b26..56fbeb58 100644 --- a/doc/_examples/ping.cc +++ b/doc/_examples/ping.cc @@ -9,28 +9,28 @@ using namespace broker; int main() { - // Setup endpoint and connect to Zeek. - endpoint ep; - auto sub = ep.make_subscriber({"/topic/test"}); - auto ss = ep.make_status_subscriber(true); - ep.peer("127.0.0.1", 9999); + // Setup endpoint and connect to Zeek. + endpoint ep; + auto sub = ep.make_subscriber({"/topic/test"}); + auto ss = ep.make_status_subscriber(true); + ep.peer("127.0.0.1", 9999); - // Wait until connection is established. - for ( bool has_peer = false; !has_peer; ) { - auto val = ss.get(); - if ( auto st = get_if(&val) ) - has_peer = st->code() == sc::peer_added; - } + // Wait until connection is established. + for (bool has_peer = false; !has_peer;) { + auto val = ss.get(); + if (auto st = get_if(&val)) + has_peer = st->code() == sc::peer_added; + } - // Do five ping / pong. - for ( int n = 0; n < 5; n++ ) { - // Send event "ping(n)". - zeek::Event ping("ping", {n}); - ep.publish("/topic/test", ping); + // Do five ping / pong. + for (int n = 0; n < 5; n++) { + // Send event "ping(n)". + zeek::Event ping("ping", {n}); + ep.publish("/topic/test", ping); - // Wait for "pong" reply event. - auto msg = sub.get(); - zeek::Event pong(move_data(msg)); - std::cout << "received " << pong.name() << pong.args() << std::endl; - } + // Wait for "pong" reply event. + auto msg = sub.get(); + zeek::Event pong(move_data(msg)); + std::cout << "received " << pong.name() << pong.args() << std::endl; + } } diff --git a/doc/_examples/pong.cc b/doc/_examples/pong.cc index 095f1aea..6e6c528d 100644 --- a/doc/_examples/pong.cc +++ b/doc/_examples/pong.cc @@ -9,28 +9,28 @@ using namespace broker; int main() { - // Setup endpoint and connect to Zeek. - endpoint ep; - auto sub = ep.make_subscriber({"/topic/test"}); - auto ss = ep.make_status_subscriber(true); - ep.listen("", 9999); + // Setup endpoint and connect to Zeek. + endpoint ep; + auto sub = ep.make_subscriber({"/topic/test"}); + auto ss = ep.make_status_subscriber(true); + ep.listen("", 9999); - // Wait until connection is established. - for ( bool has_peer = false; !has_peer; ) { - auto val = ss.get(); - if ( auto st = get_if(&val) ) - has_peer = st->code() == sc::peer_added; - } + // Wait until connection is established. + for (bool has_peer = false; !has_peer;) { + auto val = ss.get(); + if (auto st = get_if(&val)) + has_peer = st->code() == sc::peer_added; + } - // Do five ping / pong. - for ( int n = 0; n < 5; n++ ) { - // Wait for a "ping" event. - auto msg = sub.get(); - zeek::Event ping(move_data(msg)); - std::cout << "received " << ping.name() << ping.args() << std::endl; + // Do five ping / pong. + for (int n = 0; n < 5; n++) { + // Wait for a "ping" event. + auto msg = sub.get(); + zeek::Event ping(move_data(msg)); + std::cout << "received " << ping.name() << ping.args() << std::endl; - // Send event "pong" response. - zeek::Event pong("pong", {n}); - ep.publish("/topic/test", pong); - } + // Send event "pong" response. + zeek::Event pong("pong", {n}); + ep.publish("/topic/test", pong); + } } diff --git a/doc/_examples/stores.cc b/doc/_examples/stores.cc index 986e666e..dac8d880 100644 --- a/doc/_examples/stores.cc +++ b/doc/_examples/stores.cc @@ -1,62 +1,57 @@ -#include #include -#include #include +#include +#include using namespace broker; -int main(){} +int main() {} void f1() { - -// --attach-master-start + // --attach-master-start endpoint ep; auto ds = ep.attach_master("foo", backend::memory); -// --attach-master-end + // --attach-master-end -// --get-with-error-start -auto result = ds->get("foo"); -if (result) + // --get-with-error-start + auto result = ds->get("foo"); + if (result) std::cout << *result << std::endl; // Print current value of 'foo'. -else if (result.error() == ec::no_such_key) + else if (result.error() == ec::no_such_key) std::cout << "key 'foo' does not exist'" << std::endl; -else if (result.error() == ec::backend_failure) + else if (result.error() == ec::backend_failure) std::cout << "something went wrong with the backend" << std::endl; -else + else std::cout << "could not retrieve value at key 'foo'" << std::endl; -// --get-with-error-end - -/// - -// --proxy-start -// Add a value to a data store (master or clone). -ds->put("foo", 42); -// Create a proxy. -auto proxy = store::proxy{*ds}; -// Perform an asynchyronous request to look up a value. -auto id = proxy.get("foo"); -// Get a file descriptor for event loops. -auto fd = proxy.mailbox().descriptor(); -// Wait for result. -::pollfd p = {fd, POLLIN, 0}; -auto n = ::poll(&p, 1, -1); -if (n < 0) + // --get-with-error-end + + /// + + // --proxy-start + // Add a value to a data store (master or clone). + ds->put("foo", 42); + // Create a proxy. + auto proxy = store::proxy{*ds}; + // Perform an asynchyronous request to look up a value. + auto id = proxy.get("foo"); + // Get a file descriptor for event loops. + auto fd = proxy.mailbox().descriptor(); + // Wait for result. + ::pollfd p = {fd, POLLIN, 0}; + auto n = ::poll(&p, 1, -1); + if (n < 0) std::terminate(); // poll failed -if (n == 1 && p.revents & POLLIN) { + if (n == 1 && p.revents & POLLIN) { auto response = proxy.receive(); // Retrieve result, won't block now. assert(response.id == id); // Check whether we got data or an error. if (response.answer) - std::cout << *response.answer << std::endl; // may print 42 + std::cout << *response.answer << std::endl; // may print 42 else if (response.answer.error() == ec::no_such_key) - std::cout << "no such key: 'foo'" << std::endl; + std::cout << "no such key: 'foo'" << std::endl; else - std::cout << "failed to retrieve value at key 'foo'" << std::endl; -} -// --proxy-end - - + std::cout << "failed to retrieve value at key 'foo'" << std::endl; + } + // --proxy-end } - - diff --git a/doc/_examples/synopsis.cc b/doc/_examples/synopsis.cc index b63bc0a7..e18635e8 100644 --- a/doc/_examples/synopsis.cc +++ b/doc/_examples/synopsis.cc @@ -1,32 +1,31 @@ -#include #include +#include using namespace broker; -int main() -{ - endpoint ep; - ep.peer("1.2.3.4", 9999); // Connect to remote endpoint on given address/port. +int main() { + endpoint ep; + ep.peer("1.2.3.4", 9999); // Connect to remote endpoint on given address/port. - // Messages + // Messages - ep.publish("/test/t1", set{1, 2, 3}); // Publish data under a given topic. + ep.publish("/test/t1", set{1, 2, 3}); // Publish data under a given topic. - auto sub = ep.make_subscriber({"/test/t2"}); // Subscribe to incoming messages for topic. - auto msg = sub.get(); // Wait for one incoming message. - std::cout << "got data for topic " << get_topic(msg) << ": " << get_data(msg) << std::endl; + auto sub = ep.make_subscriber( + {"/test/t2"}); // Subscribe to incoming messages for topic. + auto msg = sub.get(); // Wait for one incoming message. + std::cout << "got data for topic " << get_topic(msg) << ": " << get_data(msg) + << std::endl; - // Data stores + // Data stores - auto m = ep.attach_master("yoda", backend::memory); // Create data store. + auto m = ep.attach_master("yoda", backend::memory); // Create data store. - m->put(4.2, -42); // Write into store. - m->put("bar", vector{true, 7u, now()}); + m->put(4.2, -42); // Write into store. + m->put("bar", vector{true, 7u, now()}); - if ( auto d = m->get(4.2) ) // Look up in store. - std::cout << "value of 4.2 is " << to_string(d) << std::endl; - else - std::cout << "no such key: 4.2" << std::endl; + if (auto d = m->get(4.2)) // Look up in store. + std::cout << "value of 4.2 is " << to_string(d) << std::endl; + else + std::cout << "no such key: 4.2" << std::endl; } - - diff --git a/include/broker/alm/multipath.hh b/include/broker/alm/multipath.hh index 6346f208..a669753c 100644 --- a/include/broker/alm/multipath.hh +++ b/include/broker/alm/multipath.hh @@ -19,7 +19,7 @@ struct multipath_tree { detail::monotonic_buffer_resource mem; }; -template +template class node_iterator { public: using iterator_category = std::forward_iterator_tag; @@ -140,7 +140,6 @@ private: multipath_node* first_ = nullptr; }; - class multipath_node { public: friend class multipath; diff --git a/include/broker/alm/routing_table.hh b/include/broker/alm/routing_table.hh index b67831a7..618f4420 100644 --- a/include/broker/alm/routing_table.hh +++ b/include/broker/alm/routing_table.hh @@ -68,7 +68,6 @@ public: /// versioning (stores only the latest version). Sorted by path length. std::vector versioned_paths; - routing_table_row() { versioned_paths.reserve(32); } diff --git a/include/broker/configuration.hh b/include/broker/configuration.hh index d5fee8fb..537188f3 100644 --- a/include/broker/configuration.hh +++ b/include/broker/configuration.hh @@ -234,7 +234,7 @@ private: template auto get_as(const configuration& cfg, std::string_view key) { - if constexpr (std::is_integral_v){ + if constexpr (std::is_integral_v) { std::optional res; using lim = std::numeric_limits; if constexpr (std::is_signed_v) { diff --git a/include/broker/convert.hh b/include/broker/convert.hh index 7c84f904..2bcc9e64 100644 --- a/include/broker/convert.hh +++ b/include/broker/convert.hh @@ -31,7 +31,7 @@ struct can_convert_predicate { template auto can_convert_to(const U& x) --> decltype(can_convert_predicate::check(x)) { + -> decltype(can_convert_predicate::check(x)) { return can_convert_predicate::check(x); } @@ -124,8 +124,9 @@ auto from_string(std::string_view str) -> decltype(to(str)) { template std::enable_if_t< detail::has_convert_v // must have a convert function - && !std::is_arithmetic_v // avoid ambiguitiy with default overloads - && !std::is_convertible_v, // avoid ambiguity with conversion-to-string + && !std::is_arithmetic_v // avoid ambiguitiy with default overloads + && !std::is_convertible_v, // avoid ambiguity with + // conversion-to-string std::ostream&> operator<<(std::ostream& os, const T& x) { std::string str; diff --git a/include/broker/data.hh b/include/broker/data.hh index dd685d3f..2653eaba 100644 --- a/include/broker/data.hh +++ b/include/broker/data.hh @@ -43,23 +43,9 @@ using table = std::map; /// @relates table void convert(const table& t, std::string& str); -using data_variant = std::variant< - none, - boolean, - count, - integer, - real, - std::string, - address, - subnet, - port, - timestamp, - timespan, - enum_value, - set, - table, - vector ->; +using data_variant = std::variant; /// A variant class that may store the data associated with one of several /// different primitive or compound types. @@ -417,12 +403,12 @@ bool contains_impl(const vector& xs, std::index_sequence) { /// Checks whether `xs` contains values of types `Ts...`. Performs "fuzzy" /// matching by calling `can_convert_to` for any `T` that is not part of the /// variant. -template +template bool contains(const vector& xs) { return contains_impl(xs, std::make_index_sequence{}); } -template +template bool contains(const data& x) { if (auto xs = get_if(x)) return contains(*xs); @@ -458,28 +444,28 @@ struct hash { template <> struct hash { - size_t operator()(const broker::set& x) const{ + size_t operator()(const broker::set& x) const { return broker::detail::fnv_hash(x); } }; template <> struct hash { - size_t operator()(const broker::vector& x) const{ + size_t operator()(const broker::vector& x) const { return broker::detail::fnv_hash(x); } }; template <> struct hash { - size_t operator()(const broker::table::value_type& x) const{ + size_t operator()(const broker::table::value_type& x) const { return broker::detail::fnv_hash(x); } }; template <> struct hash { - size_t operator()(const broker::table& x) const{ + size_t operator()(const broker::table& x) const { return broker::detail::fnv_hash(x); } }; diff --git a/include/broker/detail/abstract_backend.hh b/include/broker/detail/abstract_backend.hh index ff2956d7..c6054698 100644 --- a/include/broker/detail/abstract_backend.hh +++ b/include/broker/detail/abstract_backend.hh @@ -32,7 +32,8 @@ public: /// Adds one value to another value. /// @param key The key associated with the existing value to add to. /// @param value The value to add on top of the existing value at *key*. - /// @param init_type The type of data to initialize when the key doesn't exist. + /// @param init_type The type of data to initialize when the key doesn't + /// exist. /// @param t The point in time this modification took place. /// @returns `nil` on success. virtual expected add(const data& key, const data& value, @@ -65,8 +66,7 @@ public: /// @returns `true` if *key* was expired (and deleted) successfully, and /// `false` if the value cannot be expired yet, i.e., the existing expiry /// time lies in the future. - virtual expected expire(const data& key, - timestamp current_time) = 0; + virtual expected expire(const data& key, timestamp current_time) = 0; // --- inspectors ----------------------------------------------------------- diff --git a/include/broker/detail/filesystem.hh b/include/broker/detail/filesystem.hh index 36adc597..a354b450 100644 --- a/include/broker/detail/filesystem.hh +++ b/include/broker/detail/filesystem.hh @@ -8,7 +8,7 @@ #ifdef BROKER_HAS_STD_FILESYSTEM -#include +# include namespace broker::detail { @@ -32,8 +32,9 @@ inline bool is_file(const path& p) { inline bool mkdirs(const path& p) { std::error_code ec; auto rval = std::filesystem::create_directories(p, ec); - if ( ! rval ) - BROKER_ERROR("failed to make directories: " << p.native() << ":" << ec.message()); + if (!rval) + BROKER_ERROR("failed to make directories: " << p.native() << ":" + << ec.message()); return rval; } @@ -45,16 +46,18 @@ inline path dirname(path p) { inline bool remove(const path& p) { std::error_code ec; auto rval = std::filesystem::remove(p, ec); - if ( ! rval ) - BROKER_ERROR("failed to remove path: " << p.native() << ":" << ec.message()); + if (!rval) + BROKER_ERROR("failed to remove path: " << p.native() << ":" + << ec.message()); return rval; } inline bool remove_all(const path& p) { std::error_code ec; auto rval = std::filesystem::remove_all(p, ec); - if ( ! rval ) - BROKER_ERROR("failed to recursively remove path: " << p.native() << ":" << ec.message()); + if (!rval) + BROKER_ERROR("failed to recursively remove path: " << p.native() << ":" + << ec.message()); return rval; } diff --git a/include/broker/detail/flare.hh b/include/broker/detail/flare.hh index 68d89d74..839e5076 100644 --- a/include/broker/detail/flare.hh +++ b/include/broker/detail/flare.hh @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #include "broker/config.hh" #include "broker/detail/native_socket.hh" diff --git a/include/broker/detail/monotonic_buffer_resource.hh b/include/broker/detail/monotonic_buffer_resource.hh index ebfefa32..5a50f41b 100644 --- a/include/broker/detail/monotonic_buffer_resource.hh +++ b/include/broker/detail/monotonic_buffer_resource.hh @@ -16,8 +16,8 @@ public: monotonic_buffer_resource(const monotonic_buffer_resource&) = delete; - monotonic_buffer_resource& operator=(const monotonic_buffer_resource&) - = delete; + monotonic_buffer_resource& + operator=(const monotonic_buffer_resource&) = delete; ~monotonic_buffer_resource() noexcept { destroy(); diff --git a/include/broker/detail/native_socket.hh b/include/broker/detail/native_socket.hh index 0f8bed72..cf6263ee 100644 --- a/include/broker/detail/native_socket.hh +++ b/include/broker/detail/native_socket.hh @@ -11,8 +11,8 @@ namespace broker::detail { using native_socket = size_t; -constexpr native_socket invalid_native_socket - = std::numeric_limits::max(); +constexpr native_socket invalid_native_socket = + std::numeric_limits::max(); #else // BROKER_WINDOWS diff --git a/include/broker/detail/pp.hh b/include/broker/detail/pp.hh index 516c8120..1f509491 100644 --- a/include/broker/detail/pp.hh +++ b/include/broker/detail/pp.hh @@ -4,38 +4,39 @@ #define BROKER_PP_EMPTY() -#define BROKER_PP_CAT(x, y) x ## y +#define BROKER_PP_CAT(x, y) x##y #define BROKER_PP_PASTE(x, y) BROKER_PP_CAT(x, y) #ifdef _MSC_VER -#define BROKER_PP_SIZE(...) \ - BROKER_PP_PASTE( \ +# define BROKER_PP_SIZE(...) \ + BROKER_PP_PASTE( \ + BROKER_PP_SIZE_I(__VA_ARGS__, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, \ + 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, \ + 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, \ + 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, \ + 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, ), \ + BROKER_PP_EMPTY()) + +#else // _MSC_VER + +# define BROKER_PP_SIZE(...) \ BROKER_PP_SIZE_I(__VA_ARGS__, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, \ 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, \ 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, \ 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, \ - 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, ), \ - BROKER_PP_EMPTY()) - -#else // _MSC_VER - -#define BROKER_PP_SIZE(...) \ - BROKER_PP_SIZE_I(__VA_ARGS__, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, \ - 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, \ - 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, \ - 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, \ - 8, 7, 6, 5, 4, 3, 2, 1, ) + 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, ) #endif // _MSVC_VER -#define BROKER_PP_SIZE_I( \ - e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, \ - e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, \ - e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, \ - e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, \ - e62, e63, size, ...) \ +#define BROKER_PP_SIZE_I(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, \ + e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, \ + e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, \ + e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, \ + e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, \ + e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, \ + e62, e63, size, ...) \ size #define BROKER_PP_OVERLOAD(PREFIX, ...) \ diff --git a/include/broker/detail/radix_tree.hh b/include/broker/detail/radix_tree.hh index 1cee20ad..fc3805a4 100644 --- a/include/broker/detail/radix_tree.hh +++ b/include/broker/detail/radix_tree.hh @@ -31,25 +31,25 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once +#include +#include #include #include -#include -#include -#include -#include -#include #include -#include #include +#include +#include +#include +#include #include "broker/config.hh" #ifdef BROKER_USE_SSE2 -#include +# include #endif -#include #include +#include namespace broker { namespace detail { @@ -113,10 +113,8 @@ public: struct node_visit { node* n; uint16_t idx; - node_visit(node* arg_n) : n(arg_n), idx(0) { - } - node_visit(node* arg_n, uint16_t arg_i) : n(arg_n), idx(arg_i) { - } + node_visit(node* arg_n) : n(arg_n), idx(0) {} + node_visit(node* arg_n, uint16_t arg_i) : n(arg_n), idx(arg_i) {} }; node* root; @@ -128,8 +126,7 @@ public: /** * Default construct an empty container. */ - explicit radix_tree() : num_entries(0), root(nullptr) { - } + explicit radix_tree() : num_entries(0), root(nullptr) {} /** * Destructor. @@ -279,15 +276,13 @@ private: node256, }; - node(tag t) : type(t) { - } + node(tag t) : type(t) {} node(tag t, const node& other) : type(t), num_children(other.num_children), partial_len(other.partial_len), - partial(other.partial) { - } + partial(other.partial) {} tag type; uint8_t num_children = 0; @@ -296,49 +291,46 @@ private: }; /** - * A small internal node in the radix tree with only 4 children. - */ + * A small internal node in the radix tree with only 4 children. + */ struct node4 { node n = {node::tag::node4}; std::array keys = {}; std::array children = {}; node4() = default; - node4(const node& other) : n(node::tag::node4, other) { - } + node4(const node& other) : n(node::tag::node4, other) {} void add_child(node** ref, unsigned char c, node* child); void rem_child(node** ref, node** child); }; /** - * An internal node in the radix tree with 16 children. - */ + * An internal node in the radix tree with 16 children. + */ struct node16 { node n = {node::tag::node16}; std::array keys = {}; std::array children = {}; node16() = default; - node16(const node& other) : n(node::tag::node16, other) { - } + node16(const node& other) : n(node::tag::node16, other) {} void add_child(node** ref, unsigned char c, node* child); void rem_child(node** ref, node** child); }; /** - * An internal node in the radix tree with 48 children, but - * a full 256 byte field. - */ + * An internal node in the radix tree with 48 children, but + * a full 256 byte field. + */ struct node48 { node n = {node::tag::node48}; std::array keys = {}; std::array children = {}; node48() = default; - node48(const node& other) : n(node::tag::node48, other) { - } + node48(const node& other) : n(node::tag::node48, other) {} void add_child(node** ref, unsigned char c, node* child); void rem_child(node** ref, unsigned char c); @@ -352,8 +344,7 @@ private: std::array children = {}; node256() = default; - node256(const node& other) : n(node::tag::node256, other) { - } + node256(const node& other) : n(node::tag::node256, other) {} void add_child(node** ref, unsigned char c, node* child); void rem_child(node** ref, unsigned char c); @@ -366,8 +357,7 @@ private: typename node::tag type; value_type kv; - leaf(value_type arg_kv) : type(node::tag::leaf), kv(std::move(arg_kv)) { - } + leaf(value_type arg_kv) : type(node::tag::leaf), kv(std::move(arg_kv)) {} const key_type& key() const { return kv.first; @@ -479,8 +469,8 @@ typename radix_tree::iterator radix_tree::end() const { } template -typename radix_tree::mapped_type& radix_tree:: -operator[](key_type lhs) { +typename radix_tree::mapped_type& +radix_tree::operator[](key_type lhs) { iterator it = find(lhs); if (it != end()) @@ -662,7 +652,7 @@ radix_tree::find_child(node* n, unsigned char c) { #ifdef BROKER_USE_SSE2 // Compare the key to all 16 stored keys __m128i cmp = _mm_cmpeq_epi8(_mm_set1_epi8(c), - _mm_loadu_si128((__m128i*)p->keys.data())); + _mm_loadu_si128((__m128i*) p->keys.data())); // Use a mask to ignore children that don't exist int mask = (1 << n->num_children) - 1; @@ -1062,7 +1052,7 @@ void radix_tree::node16::add_child(node** ref, unsigned char c, #ifdef BROKER_USE_SSE2 // Compare the key to all 16 stored keys __m128i cmp = _mm_cmplt_epi8(_mm_set1_epi8(c), - _mm_loadu_si128((__m128i*)keys.data())); + _mm_loadu_si128((__m128i*) keys.data())); // Use a mask to ignore children that don't exist unsigned mask = (1 << n.num_children) - 1; @@ -1167,8 +1157,8 @@ void radix_tree::node4::rem_child(node** ref, node** child) { } if (prefix < N) { - int sub_prefix - = std::min(static_cast(last->partial_len), N - prefix); + int sub_prefix = std::min(static_cast(last->partial_len), + N - prefix); std::copy(last->partial.begin(), last->partial.begin() + sub_prefix, n.partial.begin() + prefix); prefix += sub_prefix; @@ -1255,18 +1245,17 @@ void radix_tree::node256::rem_child(node** ref, unsigned char c) { template radix_tree::iterator::iterator(node* arg_root, node* starting_point) - : root(arg_root), node_ptr(starting_point), ready_to_iterate(false) { -} + : root(arg_root), node_ptr(starting_point), ready_to_iterate(false) {} template -typename radix_tree::iterator::reference radix_tree::iterator:: -operator*() const { +typename radix_tree::iterator::reference +radix_tree::iterator::operator*() const { return reinterpret_cast(node_ptr)->kv; } template -typename radix_tree::iterator::pointer radix_tree::iterator:: -operator->() const { +typename radix_tree::iterator::pointer +radix_tree::iterator::operator->() const { return &reinterpret_cast(node_ptr)->kv; } @@ -1281,16 +1270,16 @@ bool radix_tree::iterator::operator!=(const iterator& other) const { } template -const typename radix_tree::iterator& radix_tree::iterator:: -operator++() { +const typename radix_tree::iterator& +radix_tree::iterator::operator++() { prepare(); increment(); return *this; } template -typename radix_tree::iterator radix_tree::iterator:: -operator++(int) { +typename radix_tree::iterator +radix_tree::iterator::operator++(int) { prepare(); auto rval = *this; increment(); @@ -1426,8 +1415,8 @@ void swap(typename radix_tree::iterator& a, } template -typename radix_tree::iterator& radix_tree::iterator:: -operator=(iterator rhs) { +typename radix_tree::iterator& +radix_tree::iterator::operator=(iterator rhs) { swap(*this, rhs); return *this; } diff --git a/include/broker/detail/sink_driver.hh b/include/broker/detail/sink_driver.hh index 52e5397d..41fafd3d 100644 --- a/include/broker/detail/sink_driver.hh +++ b/include/broker/detail/sink_driver.hh @@ -77,7 +77,7 @@ struct sink_driver_cleanup_trait { class sink_driver { public: - virtual ~sink_driver() ; + virtual ~sink_driver(); virtual void init() = 0; @@ -125,9 +125,9 @@ public: } void on_cleanup(const error& what) override { - if (!completed_) { - cleanup_(state_, what); - completed_ = true; + if (!completed_) { + cleanup_(state_, what); + completed_ = true; } } @@ -180,9 +180,9 @@ public: } void on_cleanup(const error& what) override { - if (!completed_) { - cleanup_(what); - completed_ = true; + if (!completed_) { + cleanup_(what); + completed_ = true; } } diff --git a/include/broker/detail/subscription.hh b/include/broker/detail/subscription.hh index 1967df3c..8f56e620 100644 --- a/include/broker/detail/subscription.hh +++ b/include/broker/detail/subscription.hh @@ -21,13 +21,12 @@ using topic_set = radix_tree; /// An actor with the associated topics in which it claims interest. class subscriber { public: - /// Default constructor. + /// Default constructor. subscriber() = default; - /// Construct from given actor and topic set. + /// Construct from given actor and topic set. subscriber(caf::actor a, topic_set ts) - : who(std::move(a)), subscriptions(std::move(ts)) { - } + : who(std::move(a)), subscriptions(std::move(ts)) {} caf::actor who = caf::invalid_actor; topic_set subscriptions; diff --git a/include/broker/detail/type_traits.hh b/include/broker/detail/type_traits.hh index daedec28..d196c816 100644 --- a/include/broker/detail/type_traits.hh +++ b/include/broker/detail/type_traits.hh @@ -36,8 +36,8 @@ struct are_same { template struct are_same { - static constexpr bool value - = std::is_same_v && are_same::value; + static constexpr bool value = + std::is_same_v && are_same::value; }; template @@ -65,8 +65,8 @@ auto has_apply_operator_test(U*) -> decltype(&U::operator(), std::true_type()); auto has_apply_operator_test(...) -> std::false_type; template -inline constexpr bool has_apply_operator - = decltype(has_apply_operator_test(std::declval()))::value; +inline constexpr bool has_apply_operator = + decltype(has_apply_operator_test(std::declval()))::value; template struct normalized_signature; diff --git a/include/broker/endpoint.hh b/include/broker/endpoint.hh index b2d4f459..cfbb610c 100644 --- a/include/broker/endpoint.hh +++ b/include/broker/endpoint.hh @@ -189,7 +189,7 @@ public: /// @note The function returns immediately. The endpoint receives a status /// message indicating the result of the peering operation. void peer_nosync(const std::string& address, uint16_t port, - timeout::seconds retry = timeout::seconds(10)); + timeout::seconds retry = timeout::seconds(10)); /// Initiates a peering with a remote endpoint, without waiting /// for the operation to complete. @@ -310,7 +310,7 @@ public: /// guaranteed to be called before the function returns. template worker subscribe(filter_type filter, Init init, OnNext on_next, - Cleanup cleanup) { + Cleanup cleanup) { return do_subscribe(std::move(filter), detail::make_sink_driver(std::move(init), std::move(on_next), diff --git a/include/broker/enum_value.hh b/include/broker/enum_value.hh index ec7f9c1e..5533316e 100644 --- a/include/broker/enum_value.hh +++ b/include/broker/enum_value.hh @@ -54,4 +54,4 @@ struct hash { } }; -} // namespace std; +} // namespace std diff --git a/include/broker/error.hh b/include/broker/error.hh index e4423712..a6d52918 100644 --- a/include/broker/error.hh +++ b/include/broker/error.hh @@ -207,9 +207,9 @@ error make_error(ec code, endpoint_info info, std::string description); /// in its context. /// @relates ec template -constexpr bool ec_has_network_info_v - = E == ec::peer_invalid || E == ec::peer_unavailable - || E == ec::peer_disconnect_during_handshake; +constexpr bool ec_has_network_info_v = + E == ec::peer_invalid || E == ec::peer_unavailable + || E == ec::peer_disconnect_during_handshake; /// @relates ec template @@ -326,7 +326,7 @@ private: }; class error_factory { - public: +public: template static error make(ec_constant, endpoint_info ei, std::string msg) { return make_impl(Code, std::move(ei), std::move(msg)); @@ -389,13 +389,13 @@ inline error_view make_error_view(const data& src) { #ifdef _MSC_VER -#define BROKER_TRY(...) \ - BROKER_PP_CAT(BROKER_PP_OVERLOAD(BROKER_TRY_, __VA_ARGS__)(__VA_ARGS__), \ - BROKER_PP_EMPTY()) +# define BROKER_TRY(...) \ + BROKER_PP_CAT(BROKER_PP_OVERLOAD(BROKER_TRY_, __VA_ARGS__)(__VA_ARGS__), \ + BROKER_PP_EMPTY()) #else // _MSVC_VER -#define BROKER_TRY(...) \ - BROKER_PP_OVERLOAD(BROKER_TRY_, __VA_ARGS__)(__VA_ARGS__) +# define BROKER_TRY(...) \ + BROKER_PP_OVERLOAD(BROKER_TRY_, __VA_ARGS__)(__VA_ARGS__) #endif // _MSVC_VER diff --git a/include/broker/expected.hh b/include/broker/expected.hh index 763e5c68..b8295147 100644 --- a/include/broker/expected.hh +++ b/include/broker/expected.hh @@ -29,14 +29,14 @@ public: // -- static member variables ------------------------------------------------ /// Stores whether move construct and move assign never throw. - static constexpr bool nothrow_move - = std::is_nothrow_move_constructible_v // - && std::is_nothrow_move_assignable_v; + static constexpr bool nothrow_move = + std::is_nothrow_move_constructible_v // + && std::is_nothrow_move_assignable_v; /// Stores whether copy construct and copy assign never throw. - static constexpr bool nothrow_copy - = std::is_nothrow_copy_constructible_v // - && std::is_nothrow_copy_assignable_v; + static constexpr bool nothrow_copy = + std::is_nothrow_copy_constructible_v // + && std::is_nothrow_copy_assignable_v; // -- constructors, destructors, and assignment operators -------------------- diff --git a/include/broker/fwd.hh b/include/broker/fwd.hh index c84fbe76..f27a05ed 100644 --- a/include/broker/fwd.hh +++ b/include/broker/fwd.hh @@ -94,12 +94,12 @@ using timespan = std::chrono::duration; using timestamp = std::chrono::time_point; using vector = std::vector; -using internal_command_variant - = std::variant; +using internal_command_variant = + std::variant; // -- arithmetic type aliases -------------------------------------------------- @@ -136,8 +136,8 @@ using routing_table = std::unordered_map; namespace broker { -using packed_message - = cow_tuple>; +using packed_message = + cow_tuple>; using command_message = cow_tuple; using data_message = cow_tuple; using node_message = cow_tuple; diff --git a/include/broker/internal/channel.hh b/include/broker/internal/channel.hh index c1ed4232..2ef00630 100644 --- a/include/broker/internal/channel.hh +++ b/include/broker/internal/channel.hh @@ -114,8 +114,8 @@ public: // -- implementation of the producer ----------------------------------------- /// Messages sent by the producer. - using producer_message - = std::variant; + using producer_message = + std::variant; struct default_producer_base {}; diff --git a/include/broker/internal/clone_actor.hh b/include/broker/internal/clone_actor.hh index ae39a749..1eb52364 100644 --- a/include/broker/internal/clone_actor.hh +++ b/include/broker/internal/clone_actor.hh @@ -5,9 +5,9 @@ #include #include -#include -#include #include +#include +#include #include "broker/data.hh" #include "broker/endpoint.hh" diff --git a/include/broker/internal/connector.hh b/include/broker/internal/connector.hh index 719ce1e4..d3f2fc9c 100644 --- a/include/broker/internal/connector.hh +++ b/include/broker/internal/connector.hh @@ -44,16 +44,14 @@ public: /// Signals that a remote node has connected to this peer. virtual void on_connection(connector_event_id event_id, endpoint_id peer, network_info addr, filter_type filter, - pending_connection_ptr ptr) - = 0; + pending_connection_ptr ptr) = 0; virtual void on_redundant_connection(connector_event_id event_id, - endpoint_id peer, network_info addr) - = 0; + endpoint_id peer, + network_info addr) = 0; - virtual void - on_drop(connector_event_id event_id, std::optional peer) - = 0; + virtual void on_drop(connector_event_id event_id, + std::optional peer) = 0; virtual void on_listen(connector_event_id event_id, uint16_t port) = 0; diff --git a/include/broker/internal/core_actor.hh b/include/broker/internal/core_actor.hh index b503462e..507117da 100644 --- a/include/broker/internal/core_actor.hh +++ b/include/broker/internal/core_actor.hh @@ -183,8 +183,7 @@ public: /// Connects the input and output buffers for a new peer to our central merge /// point. caf::error init_new_peer(endpoint_id peer, const network_info& addr, - const filter_type& filter, - node_consumer_res in_res, + const filter_type& filter, node_consumer_res in_res, node_producer_res out_res); /// Spin up a new background worker managing the socket and then dispatch to @@ -217,9 +216,10 @@ public: backend_options opts); /// Attaches a clone for given store to this peer. - caf::result - attach_clone(const std::string& name, double resync_interval, - double stale_interval, double mutation_buffer_interval); + caf::result attach_clone(const std::string& name, + double resync_interval, + double stale_interval, + double mutation_buffer_interval); /// Terminates all masters and clones by sending exit messages to the /// corresponding actors. @@ -303,8 +303,8 @@ public: /// Synchronizes information about the current status of a peering with the /// connector. - detail::shared_peer_status_map_ptr peer_statuses - = std::make_shared(); + detail::shared_peer_status_map_ptr peer_statuses = + std::make_shared(); /// Buffer for serializing messages. Having this as a member allows us to /// re-use the same heap-allocated buffer instead of always allocating fresh diff --git a/include/broker/internal/core_recorder.hh b/include/broker/internal/core_recorder.hh index afdefe58..de3875ef 100644 --- a/include/broker/internal/core_recorder.hh +++ b/include/broker/internal/core_recorder.hh @@ -30,7 +30,7 @@ public: } size_t remaining_records() const noexcept { - return remaining_records_ ; + return remaining_records_; } template diff --git a/include/broker/internal/flare_actor.hh b/include/broker/internal/flare_actor.hh index a71f4f80..b6026ac6 100644 --- a/include/broker/internal/flare_actor.hh +++ b/include/broker/internal/flare_actor.hh @@ -1,8 +1,8 @@ #pragma once -#include #include #include +#include #include @@ -18,7 +18,7 @@ namespace caf { namespace mixin { template <> -struct is_blocking_requester : std::true_type { }; +struct is_blocking_requester : std::true_type {}; } // namespace mixin } // namespace caf diff --git a/include/broker/internal/generator_file_reader.hh b/include/broker/internal/generator_file_reader.hh index 59a9d4f8..67548ffb 100644 --- a/include/broker/internal/generator_file_reader.hh +++ b/include/broker/internal/generator_file_reader.hh @@ -30,8 +30,8 @@ public: using file_handle_type = detail::native_socket; #endif - using read_raw_callback - = std::function)>; + using read_raw_callback = + std::function)>; generator_file_reader(file_handle_type fd, mapper_handle mapper, mapped_pointer addr, size_t file_size); diff --git a/include/broker/internal/master_actor.hh b/include/broker/internal/master_actor.hh index 7a94934e..3b3904b0 100644 --- a/include/broker/internal/master_actor.hh +++ b/include/broker/internal/master_actor.hh @@ -4,12 +4,12 @@ #include #include -#include #include +#include #include "broker/data.hh" -#include "broker/endpoint.hh" #include "broker/detail/abstract_backend.hh" +#include "broker/endpoint.hh" #include "broker/entity_id.hh" #include "broker/fwd.hh" #include "broker/internal/store_actor.hh" diff --git a/include/broker/internal/metric_exporter.hh b/include/broker/internal/metric_exporter.hh index f24d1823..a2fa479b 100644 --- a/include/broker/internal/metric_exporter.hh +++ b/include/broker/internal/metric_exporter.hh @@ -53,10 +53,11 @@ public: metric_exporter_state(Self* self, caf::actor core, metric_exporter_params&& params) - : metric_exporter_state( - self, std::move(core), std::move(params.selected_prefixes), - params.interval, std::move(params.target), std::move(params.id)) { - //nop + : metric_exporter_state(self, std::move(core), + std::move(params.selected_prefixes), + params.interval, std::move(params.target), + std::move(params.id)) { + // nop } caf::behavior make_behavior() { @@ -88,9 +89,7 @@ public: [this](atom::put, topic& new_target) { set_target(std::move(new_target)); }, - [this](atom::put, std::string& new_id) { - set_id(std::move(new_id)); - }, + [this](atom::put, std::string& new_id) { set_id(std::move(new_id)); }, [this](atom::put, filter_type& new_prefixes_filter) { set_prefixes(std::move(new_prefixes_filter)); }, @@ -185,7 +184,7 @@ public: static inline const char* name = "broker.exporter"; }; -using metric_exporter_actor - = caf::stateful_actor>; +using metric_exporter_actor = + caf::stateful_actor>; } // namespace broker::internal diff --git a/include/broker/internal/peer_filter.hh b/include/broker/internal/peer_filter.hh index df65a4a6..3e8245dd 100644 --- a/include/broker/internal/peer_filter.hh +++ b/include/broker/internal/peer_filter.hh @@ -5,8 +5,8 @@ #include -#include "broker/topic.hh" #include "broker/detail/prefix_matcher.hh" +#include "broker/topic.hh" namespace broker::internal { diff --git a/include/broker/internal/pending_connection.hh b/include/broker/internal/pending_connection.hh index 05f88d8f..5e1db7a2 100644 --- a/include/broker/internal/pending_connection.hh +++ b/include/broker/internal/pending_connection.hh @@ -21,8 +21,7 @@ public: /// @param push The resource where the connection pushes data to. virtual caf::error run(caf::actor_system& sys, caf::async::consumer_resource pull, - caf::async::producer_resource push) - = 0; + caf::async::producer_resource push) = 0; }; /// @relates pending_connection diff --git a/include/broker/internal/scoped_flare_actor.hh b/include/broker/internal/scoped_flare_actor.hh index 4fa0f9b0..83895875 100644 --- a/include/broker/internal/scoped_flare_actor.hh +++ b/include/broker/internal/scoped_flare_actor.hh @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #include namespace broker::internal { diff --git a/include/broker/internal/type_id.hh b/include/broker/internal/type_id.hh index 2e65b3fb..31c8d19e 100644 --- a/include/broker/internal/type_id.hh +++ b/include/broker/internal/type_id.hh @@ -166,12 +166,12 @@ CAF_BEGIN_TYPE_ID_BLOCK(broker, caf::first_custom_type_id) // -- STD/CAF type announcements --------------------------------------------- - BROKER_ADD_TYPE_ID((std::optional)) - BROKER_ADD_TYPE_ID((std::optional)) - BROKER_ADD_TYPE_ID((std::optional)) - BROKER_ADD_TYPE_ID((std::shared_ptr)) - BROKER_ADD_TYPE_ID((std::shared_ptr>)) - BROKER_ADD_TYPE_ID((std::vector)) + BROKER_ADD_TYPE_ID((std::optional) ) + BROKER_ADD_TYPE_ID((std::optional) ) + BROKER_ADD_TYPE_ID((std::optional) ) + BROKER_ADD_TYPE_ID((std::shared_ptr) ) + BROKER_ADD_TYPE_ID((std::shared_ptr>) ) + BROKER_ADD_TYPE_ID((std::vector) ) CAF_END_TYPE_ID_BLOCK(broker) diff --git a/include/broker/internal/web_socket.hh b/include/broker/internal/web_socket.hh index f05cf7c9..dbf71be5 100644 --- a/include/broker/internal/web_socket.hh +++ b/include/broker/internal/web_socket.hh @@ -15,8 +15,8 @@ using push_t = caf::async::producer_resource; using connect_event_t = std::pair; -using on_connect_t - = std::function; +using on_connect_t = + std::function; expected launch(caf::actor_system& sys, openssl_options_ptr ssl_cfg, std::string addr, uint16_t port, bool reuse_addr, diff --git a/include/broker/internal/wire_format.hh b/include/broker/internal/wire_format.hh index 9f8922db..79bd6784 100644 --- a/include/broker/internal/wire_format.hh +++ b/include/broker/internal/wire_format.hh @@ -237,20 +237,20 @@ inline originator_ack_msg make_originator_ack_msg() { /// Trait that translates between native @ref node_message and a binary network /// representation. class trait { - public: - /// Serializes a @ref node_message to a sequence of bytes. - bool convert(const node_message& msg, caf::byte_buffer& buf); +public: + /// Serializes a @ref node_message to a sequence of bytes. + bool convert(const node_message& msg, caf::byte_buffer& buf); - /// Deserializes a @ref node_message from a sequence of bytes. - bool convert(caf::const_byte_span bytes, node_message& msg); + /// Deserializes a @ref node_message from a sequence of bytes. + bool convert(caf::const_byte_span bytes, node_message& msg); - /// Retrieves the last error from a conversion. - const caf::error& last_error() const noexcept { - return last_error_; - } + /// Retrieves the last error from a conversion. + const caf::error& last_error() const noexcept { + return last_error_; + } - private: - caf::error last_error_; +private: + caf::error last_error_; }; } // namespace v1 @@ -262,10 +262,10 @@ struct var_msg_error { }; /// Convenience type for handling phase 1 and phase 2 messages. -using var_msg - = std::variant; +using var_msg = + std::variant; /// @relates var_msg std::string stringify(const var_msg& msg); diff --git a/include/broker/internal_command.hh b/include/broker/internal_command.hh index ea49520c..9fdef73e 100644 --- a/include/broker/internal_command.hh +++ b/include/broker/internal_command.hh @@ -31,12 +31,12 @@ std::string to_string(command_tag); // -- broadcast: actions on the key-value store such as put and erase ---------- /// Sets a value in the key-value store. -struct put_command { +struct put_command { data key; data value; std::optional expiry; entity_id publisher; - static constexpr auto tag = command_tag::action; \ + static constexpr auto tag = command_tag::action; }; /// @relates put_command @@ -59,7 +59,7 @@ struct put_unique_command { entity_id who; request_id req_id; entity_id publisher; - static constexpr auto tag = command_tag::action; \ + static constexpr auto tag = command_tag::action; }; /// @relates put_unique_command @@ -82,7 +82,7 @@ struct put_unique_result_command { entity_id who; request_id req_id; entity_id publisher; - static constexpr auto tag = command_tag::action; \ + static constexpr auto tag = command_tag::action; }; /// @relates put_unique_result_command @@ -101,7 +101,7 @@ bool inspect(Inspector& f, put_unique_result_command& x) { struct erase_command { data key; entity_id publisher; - static constexpr auto tag = command_tag::action; \ + static constexpr auto tag = command_tag::action; }; /// @relates erase_command @@ -121,7 +121,7 @@ bool inspect(Inspector& f, erase_command& x) { struct expire_command { data key; entity_id publisher; - static constexpr auto tag = command_tag::action; \ + static constexpr auto tag = command_tag::action; }; /// @relates expire_command @@ -141,7 +141,7 @@ struct add_command { data::type init_type; std::optional expiry; entity_id publisher; - static constexpr auto tag = command_tag::action; \ + static constexpr auto tag = command_tag::action; }; /// @relates add_command @@ -163,7 +163,7 @@ struct subtract_command { data value; std::optional expiry; entity_id publisher; - static constexpr auto tag = command_tag::action; \ + static constexpr auto tag = command_tag::action; }; /// @relates subtract_command @@ -172,16 +172,16 @@ bool inspect(Inspector& f, subtract_command& x) { return f // .object(x) .pretty_name("subtract") - .fields(f.field("key", x.key), // - f.field("value", x.value), // - f.field("expiry", x.expiry), // + .fields(f.field("key", x.key), // + f.field("value", x.value), // + f.field("expiry", x.expiry), // f.field("publisher", x.publisher)); } /// Drops all values. struct clear_command { entity_id publisher; - static constexpr auto tag = command_tag::action; \ + static constexpr auto tag = command_tag::action; }; /// @relates clear_command @@ -199,7 +199,7 @@ bool inspect(Inspector& f, clear_command& x) { struct attach_writer_command { sequence_number_type offset; tick_interval_type heartbeat_interval; - static constexpr auto tag = command_tag::producer_control; \ + static constexpr auto tag = command_tag::producer_control; }; /// @relates attach_writer_command @@ -294,12 +294,12 @@ bool inspect(Inspector& f, retransmit_failed_command& x) { // -- variant setup ------------------------------------------------------------ -using internal_command_variant - = std::variant; +using internal_command_variant = + std::variant; class internal_command { public: diff --git a/include/broker/message.hh b/include/broker/message.hh index 84a4fe6e..95228bc5 100644 --- a/include/broker/message.hh +++ b/include/broker/message.hh @@ -70,8 +70,8 @@ bool inspect(Inspector& f, packed_message_type& x) { } /// A Broker-internal message with a payload received from the ALM layer. -using packed_message - = cow_tuple>; +using packed_message = + cow_tuple>; /// @relates packed_message inline packed_message make_packed_message(packed_message_type type, diff --git a/include/broker/peer_info.hh b/include/broker/peer_info.hh index d10b6d01..99e6bae6 100644 --- a/include/broker/peer_info.hh +++ b/include/broker/peer_info.hh @@ -9,9 +9,9 @@ namespace broker { /// Information about a peer of an endpoint. /// @relates endpoint struct peer_info { - endpoint_info peer; ///< Information about the peer. - peer_flags flags; ///< Details about peering relationship. - peer_status status; ///< The current peering status. + endpoint_info peer; ///< Information about the peer. + peer_flags flags; ///< Details about peering relationship. + peer_status status; ///< The current peering status. }; template diff --git a/include/broker/port.hh b/include/broker/port.hh index 2773c3bb..69a59702 100644 --- a/include/broker/port.hh +++ b/include/broker/port.hh @@ -95,4 +95,4 @@ struct hash { } }; -} // namespace std; +} // namespace std diff --git a/include/broker/span.hh b/include/broker/span.hh index 3498f9e0..ceb440ac 100644 --- a/include/broker/span.hh +++ b/include/broker/span.hh @@ -47,33 +47,27 @@ public: // -- constructors, destructors, and assignment operators ------------------ - constexpr span() noexcept : memory_block(nullptr), num_elements(0) { - } + constexpr span() noexcept : memory_block(nullptr), num_elements(0) {} constexpr span(pointer ptr, size_t size) - : memory_block(ptr), num_elements(size) { - } + : memory_block(ptr), num_elements(size) {} constexpr span(pointer first, pointer last) - : memory_block(first), num_elements(static_cast(last - first)) { - } + : memory_block(first), num_elements(static_cast(last - first)) {} template constexpr span(element_type (&arr)[Size]) noexcept - : memory_block(arr), num_elements(Size) { - } + : memory_block(arr), num_elements(Size) {} template >> span(Container& xs) noexcept - : memory_block(xs.data()), num_elements(xs.size()) { - } + : memory_block(xs.data()), num_elements(xs.size()) {} template >> span(const Container& xs) noexcept - : memory_block(xs.data()), num_elements(xs.size()) { - } + : memory_block(xs.data()), num_elements(xs.size()) {} constexpr span(const span&) noexcept = default; diff --git a/include/broker/status.hh b/include/broker/status.hh index 97056328..71029f89 100644 --- a/include/broker/status.hh +++ b/include/broker/status.hh @@ -82,8 +82,8 @@ constexpr bool sc_has_endpoint_info_v = S != sc::unspecified; /// in its context. /// @relates sc template -constexpr bool sc_has_network_info_v - = S == sc::peer_added || S == sc::peer_removed || S == sc::peer_lost; +constexpr bool sc_has_network_info_v = + S == sc::peer_added || S == sc::peer_removed || S == sc::peer_lost; template <> struct can_convert_predicate { @@ -100,7 +100,6 @@ bool inspect(Inspector& f, status& x); class status : detail::equality_comparable, detail::equality_comparable, detail::equality_comparable { - public: template static status make(endpoint_info ei, std::string msg) { @@ -148,7 +147,7 @@ public: /// Retrieves an optional details about the status, if available. /// @returns A textual description of status details. - const std::string* message() const{ + const std::string* message() const { return &message_; } diff --git a/include/broker/status_subscriber.hh b/include/broker/status_subscriber.hh index 397eced4..cb862844 100644 --- a/include/broker/status_subscriber.hh +++ b/include/broker/status_subscriber.hh @@ -109,7 +109,7 @@ public: private: // -- force users to use `endpoint::make_status_subscriber` ------------------ -// status_subscriber(endpoint& ep, bool receive_statuses = false); + // status_subscriber(endpoint& ep, bool receive_statuses = false); explicit status_subscriber(subscriber impl); value_type convert(const data_message& msg); @@ -139,7 +139,7 @@ inline const T* get_if(const status_variant& d) { template inline T& get(status_variant& d) { - if ( auto rval = get_if(&d) ) + if (auto rval = get_if(&d)) return *rval; else throw bad_variant_access{}; @@ -147,7 +147,7 @@ inline T& get(status_variant& d) { template inline const T& get(const status_variant& d) { - if ( auto rval = get_if(&d) ) + if (auto rval = get_if(&d)) return *rval; else throw bad_variant_access{}; diff --git a/include/broker/store.hh b/include/broker/store.hh index b29edeee..0e39e74b 100644 --- a/include/broker/store.hh +++ b/include/broker/store.hh @@ -187,7 +187,7 @@ public: void increment(data key, data amount, std::optional expiry = {}) { auto init_type = data::type::none; - switch ( amount.get_type() ) { + switch (amount.get_type()) { case data::type::count: init_type = data::type::count; break; @@ -235,7 +235,8 @@ public: /// Inserts an index into a table. /// @param key The key of the table into which to insert the value. /// @param index The index to insert. - /// @param value The value to associated with the inserted index. For sets, this is ignored. + /// @param value The value to associated with the inserted index. For sets, + /// this is ignored. /// @param expiry An optional new expiration time for *key*. void insert_into(data key, data index, data value, std::optional expiry = {}) { @@ -277,8 +278,8 @@ public: /// @param timeout The maximum amount of time this function may block. /// @returns `true` if the frontend actor responded before the timeout, /// `false` otherwise. - [[nodiscard]] bool await_idle(timespan timeout - = defaults::store::await_idle_timeout); + [[nodiscard]] bool + await_idle(timespan timeout = defaults::store::await_idle_timeout); /// Asynchronously runs `callback(true)` when the frontend actor reached an /// IDLE state or `callback(false)` if the optional timeout triggered first @@ -311,7 +312,7 @@ private: /// "add". This is the backend for a number of the modifiers methods. /// @param key The key of the key-value pair. /// @param value The value of the key-value pair. - /// @param init_type The type of data to initialize when the key does not exist. + /// @param init_type The type of data to create when the key does not exist. /// @param expiry An optional new expiration time for *key*. void add(data key, data value, data::type init_type, std::optional expiry = {}); diff --git a/include/broker/subnet.hh b/include/broker/subnet.hh index e2567456..0bda2530 100644 --- a/include/broker/subnet.hh +++ b/include/broker/subnet.hh @@ -74,4 +74,4 @@ struct hash { } }; -} // namespace std; +} // namespace std diff --git a/include/broker/subscriber.hh b/include/broker/subscriber.hh index 25f58601..e3742278 100644 --- a/include/broker/subscriber.hh +++ b/include/broker/subscriber.hh @@ -8,8 +8,8 @@ #include "broker/topic.hh" #include "broker/worker.hh" -#include #include +#include namespace broker { diff --git a/include/broker/telemetry/counter.hh b/include/broker/telemetry/counter.hh index f1f0d502..1812dd90 100644 --- a/include/broker/telemetry/counter.hh +++ b/include/broker/telemetry/counter.hh @@ -48,7 +48,7 @@ public: counter& operator=(const counter&) noexcept = default; - /// Increments the value by 1. + /// Increments the value by 1. void inc() noexcept { telemetry::inc(hdl_); } @@ -59,8 +59,8 @@ public: telemetry::inc(hdl_, amount); } - /// Increments the value by 1. - /// @return The new value. + /// Increments the value by 1. + /// @return The new value. template std::enable_if_t, V> operator++() noexcept { return telemetry::inc(hdl_); @@ -71,7 +71,7 @@ public: return telemetry::value(hdl_); } - /// @return Whether @c this and @p other refer to the same counter. + /// @return Whether @c this and @p other refer to the same counter. constexpr bool is_same_as(counter other) const noexcept { return hdl_ == other.hdl_; } @@ -81,7 +81,7 @@ private: }; /// @relates counter -template +template constexpr bool operator==(counter x, counter y) { return x.is_same_as(y); } @@ -111,7 +111,7 @@ public: /// Returns the metrics handle for given labels, creating a new instance /// lazily if necessary. counter get_or_add(span labels) { - if constexpr (std::is_same_v) + if constexpr (std::is_same_v) return counter{dbl_counter_get_or_add(super::hdl_, labels)}; else return counter{int_counter_get_or_add(super::hdl_, labels)}; @@ -122,14 +122,14 @@ public: return get_or_add(span{labels.begin(), labels.size()}); } - /// @return Whether @c this and @p other refer to the same family. + /// @return Whether @c this and @p other refer to the same family. constexpr bool is_same_as(counter_family other) const noexcept { return hdl_ == other.hdl_; } }; /// @relates counter_family -template +template constexpr bool operator==(counter_family x, counter_family y) { return x.is_same_as(y); } diff --git a/include/broker/telemetry/fwd.hh b/include/broker/telemetry/fwd.hh index 2951910e..99fffb32 100644 --- a/include/broker/telemetry/fwd.hh +++ b/include/broker/telemetry/fwd.hh @@ -266,13 +266,13 @@ template struct counter_hdl_oracle; template <> -struct counter_hdl_oracle{ +struct counter_hdl_oracle { using fam_type = telemetry::dbl_counter_family_hdl; using hdl_type = telemetry::dbl_counter_hdl; }; template <> -struct counter_hdl_oracle{ +struct counter_hdl_oracle { using fam_type = telemetry::int_counter_family_hdl; using hdl_type = telemetry::int_counter_hdl; }; @@ -287,13 +287,13 @@ template struct gauge_hdl_oracle; template <> -struct gauge_hdl_oracle{ +struct gauge_hdl_oracle { using fam_type = telemetry::dbl_gauge_family_hdl; using hdl_type = telemetry::dbl_gauge_hdl; }; template <> -struct gauge_hdl_oracle{ +struct gauge_hdl_oracle { using fam_type = telemetry::int_gauge_family_hdl; using hdl_type = telemetry::int_gauge_hdl; }; @@ -308,13 +308,13 @@ template struct histogram_hdl_oracle; template <> -struct histogram_hdl_oracle{ +struct histogram_hdl_oracle { using fam_type = telemetry::dbl_histogram_family_hdl; using hdl_type = telemetry::dbl_histogram_hdl; }; template <> -struct histogram_hdl_oracle{ +struct histogram_hdl_oracle { using fam_type = telemetry::int_histogram_family_hdl; using hdl_type = telemetry::int_histogram_hdl; }; diff --git a/include/broker/telemetry/gauge.hh b/include/broker/telemetry/gauge.hh index d36cd68d..601958e0 100644 --- a/include/broker/telemetry/gauge.hh +++ b/include/broker/telemetry/gauge.hh @@ -58,7 +58,7 @@ public: gauge& operator=(const gauge&) noexcept = default; - /// Increments the value by 1. + /// Increments the value by 1. void inc() noexcept { telemetry::inc(hdl_); } @@ -69,8 +69,8 @@ public: telemetry::inc(hdl_, amount); } - /// Increments the value by 1. - /// @return The new value. + /// Increments the value by 1. + /// @return The new value. template std::enable_if_t, V> operator++() noexcept { return telemetry::inc(hdl_); @@ -94,7 +94,7 @@ public: return telemetry::value(hdl_); } - /// @return Whether @c this and @p other refer to the same gauge. + /// @return Whether @c this and @p other refer to the same gauge. constexpr bool is_same_as(gauge other) const noexcept { return hdl_ == other.hdl_; } @@ -104,7 +104,7 @@ private: }; /// @relates gauge -template +template constexpr bool operator==(gauge x, gauge y) { return x.is_same_as(y); } @@ -134,7 +134,7 @@ public: /// Returns the metrics handle for given labels, creating a new instance /// lazily if necessary. gauge get_or_add(span labels) { - if constexpr (std::is_same_v) + if constexpr (std::is_same_v) return gauge{dbl_gauge_get_or_add(super::hdl_, labels)}; else return gauge{int_gauge_get_or_add(super::hdl_, labels)}; @@ -145,14 +145,14 @@ public: return get_or_add(span{labels.begin(), labels.size()}); } - /// @return Whether @c this and @p other refer to the same family. + /// @return Whether @c this and @p other refer to the same family. constexpr bool is_same_as(gauge_family other) const noexcept { return hdl_ == other.hdl_; } }; /// @relates gauge_family -template +template constexpr bool operator==(gauge_family x, gauge_family y) { return x.is_same_as(y); } diff --git a/include/broker/telemetry/histogram.hh b/include/broker/telemetry/histogram.hh index 6b258b4b..126b1ae7 100644 --- a/include/broker/telemetry/histogram.hh +++ b/include/broker/telemetry/histogram.hh @@ -24,8 +24,8 @@ public: histogram& operator=(const histogram&) noexcept = default; - /// Increments all buckets with an upper bound less than or equal to @p value - /// by one and adds @p value to the total sum of all observed values. + /// Increments all buckets with an upper bound less than or equal to @p value + /// by one and adds @p value to the total sum of all observed values. void observe(T value) noexcept { return telemetry::observe(hdl_, value); } @@ -62,7 +62,7 @@ private: }; /// @relates histogram -template +template constexpr bool operator==(histogram x, histogram y) { return x.is_same_as(y); } @@ -92,7 +92,7 @@ public: /// Returns the metrics handle for given labels, creating a new instance /// lazily if necessary. histogram get_or_add(span labels) { - if constexpr (std::is_same_v) + if constexpr (std::is_same_v) return histogram{dbl_histogram_get_or_add(super::hdl_, labels)}; else return histogram{int_histogram_get_or_add(super::hdl_, labels)}; @@ -103,14 +103,14 @@ public: return get_or_add(span{labels.begin(), labels.size()}); } - /// @return Whether @c this and @p other refer to the same family. + /// @return Whether @c this and @p other refer to the same family. constexpr bool is_same_as(histogram_family other) const noexcept { return hdl_ == other.hdl_; } }; /// @relates histogram_family -template +template constexpr bool operator==(histogram_family x, histogram_family y) { return x.is_same_as(y); } diff --git a/include/broker/telemetry/metric_family.hh b/include/broker/telemetry/metric_family.hh index 3d3ff755..31fb8c66 100644 --- a/include/broker/telemetry/metric_family.hh +++ b/include/broker/telemetry/metric_family.hh @@ -29,18 +29,18 @@ public: } /// @return The names for all label dimensions. - span label_names() const noexcept{ + span label_names() const noexcept { return telemetry::label_names(hdl_); } /// @return A short explanation of the metric. - std::string_view helptext() const noexcept{ + std::string_view helptext() const noexcept { return telemetry::helptext(hdl_); } /// @return The unit of measurement, preferably a base unit such as @c bytes /// or @c seconds. Dimensionless counts return the pseudo-unit @c 1. - std::string_view unit() const noexcept{ + std::string_view unit() const noexcept { return telemetry::unit(hdl_); } diff --git a/include/broker/telemetry/metric_registry.hh b/include/broker/telemetry/metric_registry.hh index 43cc3a1b..4b2e6fd5 100644 --- a/include/broker/telemetry/metric_registry.hh +++ b/include/broker/telemetry/metric_registry.hh @@ -96,8 +96,8 @@ public: span labels, std::string_view helptext, std::string_view unit = "1", bool is_sum = false) { return with_label_names(labels, [&, this](auto labelNames) { - auto family - = counter_family(pre, name, labelNames, helptext, unit, is_sum); + auto family = counter_family(pre, name, labelNames, helptext, unit, + is_sum); return family.getOrAdd(labels); }); } @@ -185,8 +185,8 @@ public: std::string_view helptext, std::string_view unit = "1", bool is_sum = false) { return with_label_names(labels, [&, this](auto labelNames) { - auto family - = gauge_family(pre, name, labelNames, helptext, unit, is_sum); + auto family = gauge_family(pre, name, labelNames, helptext, unit, + is_sum); return family.getOrAdd(labels); }); } @@ -260,14 +260,16 @@ public: std::string_view helptext, std::string_view unit = "1", bool is_sum = false) { if constexpr (std::is_same_v) { - auto hdl = impl_->int_histogram_fam( - pre, name, labels, default_upper_bounds, helptext, unit, is_sum); + auto hdl = impl_->int_histogram_fam(pre, name, labels, + default_upper_bounds, helptext, unit, + is_sum); return int_histogram_family{hdl}; } else { static_assert(std::is_same_v, "metrics only support int64_t and double values"); - auto hdl = impl_->dbl_histogram_fam( - pre, name, labels, default_upper_bounds, helptext, unit, is_sum); + auto hdl = impl_->dbl_histogram_fam(pre, name, labels, + default_upper_bounds, helptext, unit, + is_sum); return dbl_histogram_family{hdl}; } } @@ -304,30 +306,31 @@ public: * @p default_upper_bounds via run-time configuration. */ template - histogram - histogram_instance(std::string_view pre, std::string_view name, - span labels, - const_span default_upper_bounds, - std::string_view helptext, std::string_view unit = "1", - bool is_sum = false) { + histogram histogram_instance(std::string_view pre, std::string_view name, + span labels, + const_span default_upper_bounds, + std::string_view helptext, + std::string_view unit = "1", + bool is_sum = false) { return with_label_names(labels, [&, this](auto labelNames) { - auto family = histogram_family( - pre, name, labelNames, default_upper_bounds, helptext, unit, is_sum); + auto family = histogram_family(pre, name, labelNames, + default_upper_bounds, helptext, unit, + is_sum); return family.getOrAdd(labels); }); } /// @copdoc histogram_instance template - histogram - histogram_instance(std::string_view pre, std::string_view name, - std::initializer_list labels, - const_span default_upper_bounds, - std::string_view helptext, std::string_view unit = "1", - bool is_sum = false) { + histogram histogram_instance(std::string_view pre, std::string_view name, + std::initializer_list labels, + const_span default_upper_bounds, + std::string_view helptext, + std::string_view unit = "1", + bool is_sum = false) { auto lbls = span{labels.begin(), labels.size()}; - return histogram_instance(pre, name, lbls, default_upper_bounds, - helptext, unit, is_sum); + return histogram_instance(pre, name, lbls, default_upper_bounds, helptext, + unit, is_sum); } /** @@ -351,11 +354,11 @@ public: * @p default_upper_bounds via run-time configuration. */ template - histogram - histogram_singleton(std::string_view pre, std::string_view name, - const_span default_upper_bounds, - std::string_view helptext, std::string_view unit = "1", - bool is_sum = false) { + histogram histogram_singleton(std::string_view pre, std::string_view name, + const_span default_upper_bounds, + std::string_view helptext, + std::string_view unit = "1", + bool is_sum = false) { auto lbls = span{}; auto fam = histogram_family(pre, name, lbls, default_upper_bounds, helptext, unit, is_sum); diff --git a/include/broker/telemetry/metric_registry_impl.hh b/include/broker/telemetry/metric_registry_impl.hh index de6319d5..cd831e4b 100644 --- a/include/broker/telemetry/metric_registry_impl.hh +++ b/include/broker/telemetry/metric_registry_impl.hh @@ -16,26 +16,22 @@ class metrics_collector { public: virtual void operator()(const metric_family_hdl* family, const dbl_counter_hdl* counter, - const_label_list labels) - = 0; + const_label_list labels) = 0; virtual void operator()(const metric_family_hdl* family, const int_counter_hdl* counter, - const_label_list labels) - = 0; + const_label_list labels) = 0; virtual void operator()(const metric_family_hdl* family, - const dbl_gauge_hdl* gauge, const_label_list labels) - = 0; + const dbl_gauge_hdl* gauge, + const_label_list labels) = 0; virtual void operator()(const metric_family_hdl* family, - const int_gauge_hdl* gauge, const_label_list labels) - = 0; + const int_gauge_hdl* gauge, + const_label_list labels) = 0; virtual void operator()(const metric_family_hdl* family, const dbl_histogram_hdl* histogram, - const_label_list labels) - = 0; + const_label_list labels) = 0; virtual void operator()(const metric_family_hdl* family, const int_histogram_hdl* histogram, - const_label_list labels) - = 0; + const_label_list labels) = 0; }; class metric_registry_impl { @@ -53,40 +49,36 @@ public: virtual int_counter_family_hdl* int_counter_fam(std::string_view pre, std::string_view name, span labels, - std::string_view helptext, std::string_view unit, bool is_sum) - = 0; + std::string_view helptext, std::string_view unit, + bool is_sum) = 0; virtual dbl_counter_family_hdl* dbl_counter_fam(std::string_view pre, std::string_view name, span labels, - std::string_view helptext, std::string_view unit, bool is_sum) - = 0; + std::string_view helptext, std::string_view unit, + bool is_sum) = 0; virtual int_gauge_family_hdl* int_gauge_fam(std::string_view pre, std::string_view name, span labels, std::string_view helptext, - std::string_view unit, bool is_sum) - = 0; + std::string_view unit, bool is_sum) = 0; virtual dbl_gauge_family_hdl* dbl_gauge_fam(std::string_view pre, std::string_view name, span labels, std::string_view helptext, - std::string_view unit, bool is_sum) - = 0; + std::string_view unit, bool is_sum) = 0; virtual int_histogram_family_hdl* int_histogram_fam(std::string_view pre, std::string_view name, span labels, span ubounds, std::string_view helptext, - std::string_view unit, bool is_sum) - = 0; + std::string_view unit, bool is_sum) = 0; virtual dbl_histogram_family_hdl* dbl_histogram_fam(std::string_view pre, std::string_view name, span labels, span ubounds, std::string_view helptext, - std::string_view unit, bool is_sum) - = 0; + std::string_view unit, bool is_sum) = 0; // Collect metrics. virtual void collect(metrics_collector& collector) = 0; diff --git a/include/broker/topic.hh b/include/broker/topic.hh index e7d77dcd..bd26dfd5 100644 --- a/include/broker/topic.hh +++ b/include/broker/topic.hh @@ -28,8 +28,8 @@ public: static constexpr std::string_view statuses_str = "<$>/local/data/statuses"; - static constexpr std::string_view store_events_str - = "<$>/local/data/store-events"; + static constexpr std::string_view store_events_str = + "<$>/local/data/store-events"; static topic master_suffix(); @@ -133,7 +133,7 @@ bool is_internal(const topic& x); /// Converts a string to a topic. /// @param str The string to convert. /// @returns The topic according to *str*. -broker::topic operator "" _t(const char* str, size_t); +broker::topic operator"" _t(const char* str, size_t); namespace std { diff --git a/include/broker/worker.hh b/include/broker/worker.hh index 06b577f6..84439143 100644 --- a/include/broker/worker.hh +++ b/include/broker/worker.hh @@ -1,7 +1,7 @@ #pragma once -#include "broker/detail/comparable.hh" #include "broker/config.hh" +#include "broker/detail/comparable.hh" #include #include diff --git a/include/broker/zeek.hh b/include/broker/zeek.hh index a3688d72..ff466921 100644 --- a/include/broker/zeek.hh +++ b/include/broker/zeek.hh @@ -20,15 +20,15 @@ public: }; Type type() const { - if ( as_vector().size() < 2 ) + if (as_vector().size() < 2) return Type::Invalid; auto cp = get_if(&as_vector()[1]); - if ( ! cp ) + if (!cp) return Type::Invalid; - if ( *cp > Type::MAX ) + if (*cp > Type::MAX) return Type::Invalid; return Type(*cp); @@ -52,7 +52,7 @@ public: vector& as_vector() { return get(data_); - } + } operator data() const { return as_data(); @@ -61,20 +61,20 @@ public: static Type type(const data& msg) { auto vp = get_if(&msg); - if ( ! vp ) + if (!vp) return Type::Invalid; auto& v = *vp; - if ( v.size() < 2 ) + if (v.size() < 2) return Type::Invalid; auto cp = get_if(&v[1]); - if ( ! cp ) + if (!cp) return Type::Invalid; - if ( *cp > Type::MAX ) + if (*cp > Type::MAX) return Type::Invalid; return Type(*cp); @@ -82,18 +82,16 @@ public: protected: Message(Type type, vector content) - : data_(vector{ProtocolVersion, count(type), std::move(content)}) { - } + : data_(vector{ProtocolVersion, count(type), std::move(content)}) {} - Message(data msg) : data_(std::move(msg)) { - } + Message(data msg) : data_(std::move(msg)) {} data data_; }; /// A Zeek event. class Event : public Message { - public: +public: Event(std::string name, vector args) : Message(Message::Type::Event, {std::move(name), std::move(args)}) {} @@ -116,27 +114,27 @@ class Event : public Message { } bool valid() const { - if ( as_vector().size() < 3 ) + if (as_vector().size() < 3) return false; auto vp = get_if(&(as_vector()[2])); - if ( ! vp ) + if (!vp) return false; auto& v = *vp; - if ( v.size() < 2 ) + if (v.size() < 2) return false; auto name_ptr = get_if(&v[0]); - if ( ! name_ptr ) + if (!name_ptr) return false; auto args_ptr = get_if(&v[1]); - if ( ! args_ptr ) + if (!args_ptr) return false; return true; @@ -145,9 +143,8 @@ class Event : public Message { /// A batch of other messages. class Batch : public Message { - public: - Batch(vector msgs) - : Message(Message::Type::Batch, std::move(msgs)) {} +public: + Batch(vector msgs) : Message(Message::Type::Batch, std::move(msgs)) {} Batch(data msg) : Message(std::move(msg)) {} @@ -160,12 +157,12 @@ class Batch : public Message { } bool valid() const { - if ( as_vector().size() < 3 ) + if (as_vector().size() < 3) return false; auto vp = get_if(&(as_vector()[2])); - if ( ! vp ) + if (!vp) return false; return true; @@ -180,11 +177,9 @@ public: data fields_data) : Message(Message::Type::LogCreate, {std::move(stream_id), std::move(writer_id), - std::move(writer_info), std::move(fields_data)}) { - } + std::move(writer_info), std::move(fields_data)}) {} - LogCreate(data msg) : Message(std::move(msg)) { - } + LogCreate(data msg) : Message(std::move(msg)) {} const enum_value& stream_id() const { return get(get(as_vector()[2])[0]); @@ -219,23 +214,23 @@ public: } bool valid() const { - if ( as_vector().size() < 3 ) + if (as_vector().size() < 3) return false; auto vp = get_if(&(as_vector()[2])); - if ( ! vp ) + if (!vp) return false; auto& v = *vp; - if ( v.size() < 4 ) + if (v.size() < 4) return false; - if ( ! get_if(&v[0]) ) + if (!get_if(&v[0])) return false; - if ( ! get_if(&v[1]) ) + if (!get_if(&v[1])) return false; return true; @@ -249,12 +244,10 @@ public: LogWrite(enum_value stream_id, enum_value writer_id, data path, data serial_data) : Message(Message::Type::LogWrite, - {std::move(stream_id), std::move(writer_id), - std::move(path), std::move(serial_data)}) { - } + {std::move(stream_id), std::move(writer_id), std::move(path), + std::move(serial_data)}) {} - LogWrite(data msg) : Message(std::move(msg)) { - } + LogWrite(data msg) : Message(std::move(msg)) {} const enum_value& stream_id() const { return get(get(as_vector()[2])[0]); @@ -289,23 +282,23 @@ public: } bool valid() const { - if ( as_vector().size() < 3 ) + if (as_vector().size() < 3) return false; auto vp = get_if(&(as_vector()[2])); - if ( ! vp ) + if (!vp) return false; auto& v = *vp; - if ( v.size() < 4 ) + if (v.size() < 4) return false; - if ( ! get_if(&v[0]) ) + if (!get_if(&v[0])) return false; - if ( ! get_if(&v[1]) ) + if (!get_if(&v[1])) return false; return true; @@ -315,12 +308,10 @@ public: class IdentifierUpdate : public Message { public: IdentifierUpdate(std::string id_name, data id_value) - : Message(Message::Type::IdentifierUpdate, {std::move(id_name), - std::move(id_value)}) { - } + : Message(Message::Type::IdentifierUpdate, + {std::move(id_name), std::move(id_value)}) {} - IdentifierUpdate(data msg) : Message(std::move(msg)) { - } + IdentifierUpdate(data msg) : Message(std::move(msg)) {} const std::string& id_name() const { return get(get(as_vector()[2])[0]); @@ -339,20 +330,20 @@ public: } bool valid() const { - if ( as_vector().size() < 3 ) + if (as_vector().size() < 3) return false; auto vp = get_if(&(as_vector()[2])); - if ( ! vp ) + if (!vp) return false; auto& v = *vp; - if ( v.size() < 2 ) + if (v.size() < 2) return false; - if ( ! get_if(&v[0]) ) + if (!get_if(&v[0])) return false; return true; diff --git a/src/BrokerConfig.cmake.in b/src/BrokerConfig.cmake.in index 8443f031..97562c76 100644 --- a/src/BrokerConfig.cmake.in +++ b/src/BrokerConfig.cmake.in @@ -1,22 +1,23 @@ -@PACKAGE_INIT@ +@PACKAGE_INIT @ -include(CMakeFindDependencyMacro) + include(CMakeFindDependencyMacro) -set(CMAKE_THREAD_PREFER_PTHREAD ON) -set(THREADS_PREFER_PTHREAD_FLAG ON) -find_dependency(Threads REQUIRED) + set(CMAKE_THREAD_PREFER_PTHREAD ON) set(THREADS_PREFER_PTHREAD_FLAG ON) + find_dependency(Threads REQUIRED) -find_dependency(OpenSSL REQUIRED) + find_dependency(OpenSSL REQUIRED) -find_dependency(CAF @CAF_VERSION@ REQUIRED COMPONENTS core io) + find_dependency(CAF @CAF_VERSION @REQUIRED COMPONENTS core io) -include("${CMAKE_CURRENT_LIST_DIR}/BrokerTargets.cmake") + include("${CMAKE_CURRENT_LIST_DIR}/BrokerTargets.cmake") -set(BROKER_LIBRARY "@BROKER_LIBRARY@" CACHE INTERNAL "name of the Broker library target") + set(BROKER_LIBRARY "@BROKER_LIBRARY@" CACHE INTERNAL + "name of the Broker library target") -function(set_include_dir) - get_target_property(dirs ${BROKER_LIBRARY} INTERFACE_INCLUDE_DIRECTORIES) - set(BROKER_INCLUDE_DIR "${dirs}" CACHE INTERNAL "extra include directories") -endfunction() + function(set_include_dir) get_target_property(dirs ${ + BROKER_LIBRARY} INTERFACE_INCLUDE_DIRECTORIES) + set(BROKER_INCLUDE_DIR "${dirs}" CACHE INTERNAL + "extra include directories") + endfunction() -set_include_dir() + set_include_dir() diff --git a/src/address.cc b/src/address.cc index 5eed9710..447d24d9 100644 --- a/src/address.cc +++ b/src/address.cc @@ -27,8 +27,8 @@ static constexpr bool is_little_endian = true; #endif -constexpr std::array v4_mapped_prefix - = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}}; +constexpr std::array v4_mapped_prefix = { + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}}; auto to_array(const uint32_t* bytes, address::family fam, address::byte_order order) { @@ -90,7 +90,7 @@ address& address::operator=(const address& other) noexcept { static uint32_t bit_mask32(int bottom_bits) { if (bottom_bits >= 32) return 0xffffffff; - return (((uint32_t)1) << bottom_bits) - 1; + return (((uint32_t) 1) << bottom_bits) - 1; } bool address::mask(uint8_t top_bits_to_keep) { @@ -99,8 +99,8 @@ bool address::mask(uint8_t top_bits_to_keep) { uint32_t mask[4] = {0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff}; auto res = std::ldiv(top_bits_to_keep, 32); if (res.quot < 4) - mask[res.quot] = caf::detail::to_network_order(mask[res.quot] - & ~bit_mask32(32 - res.rem)); + mask[res.quot] = + caf::detail::to_network_order(mask[res.quot] & ~bit_mask32(32 - res.rem)); for (auto i = res.quot + 1; i < 4; ++i) mask[i] = 0; auto p = reinterpret_cast(&bytes()); diff --git a/src/alm/multipath.cc b/src/alm/multipath.cc index 449ac86d..6af3168d 100644 --- a/src/alm/multipath.cc +++ b/src/alm/multipath.cc @@ -96,8 +96,7 @@ multipath_node::~multipath_node() { } bool multipath_node::equals(const multipath_node& other) const noexcept { - return id_ == other.id_ - && is_receiver_ == other.is_receiver_ + return id_ == other.id_ && is_receiver_ == other.is_receiver_ && down_.equals(other.down_); } diff --git a/src/alm/routing_table.cc b/src/alm/routing_table.cc index 79026c2c..1ec5c0ef 100644 --- a/src/alm/routing_table.cc +++ b/src/alm/routing_table.cc @@ -31,10 +31,8 @@ routing_table_row* find_row(routing_table& tbl, const endpoint_id& peer) { return nullptr; } -bool add_or_update_path(routing_table& tbl, - const endpoint_id& peer, - std::vector path, - vector_timestamp ts) { +bool add_or_update_path(routing_table& tbl, const endpoint_id& peer, + std::vector path, vector_timestamp ts) { auto& row = tbl[peer]; auto& paths = row.versioned_paths; auto i = std::lower_bound(paths.begin(), paths.end(), path, path_less); diff --git a/src/broker-gateway.cc b/src/broker-gateway.cc index 4b6ca6d7..0808d8aa 100644 --- a/src/broker-gateway.cc +++ b/src/broker-gateway.cc @@ -105,16 +105,14 @@ class config : public configuration { .add("retry-interval", "time between peering connection attempts in seconds"); opt_group{custom_options_, "internal"} - .add("peers", - "list of peers to connect to on startup in " - "tcp://$host:$port notation") + .add("peers", "list of peers to connect to on startup in " + "tcp://$host:$port notation") .add("port", "local port to listen for incoming peerings ") .add(internal.disable_forwarding, "disable-forwarding", "disable peer-to-peer message forwarding in the internal domain"); opt_group{custom_options_, "external"} - .add("peers", - "list of peers to connect to on startup in " - "tcp://$host:$port notation") + .add("peers", "list of peers to connect to on startup in " + "tcp://$host:$port notation") .add("port", "local port to listen for incoming peerings ") .add(external.disable_forwarding, "disable-forwarding", "disable peer-to-peer message forwarding in the external domain"); @@ -136,8 +134,8 @@ int run(gateway& gw) { auto try_listen = [&](caf::string_view key) { if (auto local_port = get_as(cfg, key)) { auto p = caf::starts_with(key, "internal.") - ? gw.listen_internal({}, *local_port) - : gw.listen_external({}, *local_port); + ? gw.listen_internal({}, *local_port) + : gw.listen_external({}, *local_port); if (p == 0) { err::println("unable to open port ", *local_port); return false; @@ -148,8 +146,8 @@ int run(gateway& gw) { }; if (!try_listen("internal.local-port") || !try_listen("external.local-port")) return EXIT_FAILURE; - if (auto peering_failures - = gw.peer(get_or(cfg, "internal.peers", uri_list{}), + if (auto peering_failures = + gw.peer(get_or(cfg, "internal.peers", uri_list{}), get_or(cfg, "internal.peers", uri_list{}), timeout::seconds{get_or(cfg, "retry-interval", size_t{10})}); !peering_failures.empty()) { diff --git a/src/broker-node.cc b/src/broker-node.cc index aedeb707..c9f5acec 100644 --- a/src/broker-node.cc +++ b/src/broker-node.cc @@ -44,8 +44,8 @@ using std::string; using broker::count; using broker::data; -using broker::internal::native; using broker::topic; +using broker::internal::native; namespace atom = broker::internal::atom; @@ -394,7 +394,7 @@ void pong_mode(broker::endpoint& ep, topic_list topics) { int main(int argc, char** argv) { broker::endpoint::system_guard sys_guard; // Initialize global state. - setvbuf(stdout, NULL, _IOLBF, 0); // Always line-buffer stdout. + setvbuf(stdout, NULL, _IOLBF, 0); // Always line-buffer stdout. // Parse CLI parameters using our config. broker::configuration cfg{broker::skip_init}; extend_config(cfg); @@ -469,7 +469,7 @@ int main(int argc, char** argv) { // Connect to peers. auto peers = get_or(ep, "peers", uri_list{}); for (auto& peer : peers) { - if (auto info = broker::to(peer)){ + if (auto info = broker::to(peer)) { verbose::println("connect to ", info->address, " on port ", info->port, " ..."); if (!ep.peer(*info)) diff --git a/src/broker-pipe.cc b/src/broker-pipe.cc index aa284cc9..5aef59ca 100644 --- a/src/broker-pipe.cc +++ b/src/broker-pipe.cc @@ -31,7 +31,7 @@ #include "broker/topic.hh" #ifndef BROKER_WINDOWS -#include +# include #endif // BROKER_WINDOWS namespace atom = broker::internal::atom; @@ -132,7 +132,7 @@ void publish_mode_select(broker::endpoint& ep, const std::string& topic_str, #endif // BROKER_WINDOWS void subscribe_mode_blocking(broker::endpoint& ep, const std::string& topic_str, - size_t cap) { + size_t cap) { auto in = ep.make_subscriber({topic_str}); std::string line; for (size_t i = 0; i < cap; ++i) { @@ -145,14 +145,14 @@ void subscribe_mode_blocking(broker::endpoint& ep, const std::string& topic_str, #ifdef BROKER_WINDOWS -void subscribe_mode_select(broker::endpoint&, const std::string&, size_t ) { +void subscribe_mode_select(broker::endpoint&, const std::string&, size_t) { std::cerr << "*** select mode not available in MSVC version of Broker\n"; } #else // BROKER_WINDOWS void subscribe_mode_select(broker::endpoint& ep, const std::string& topic_str, - size_t cap) { + size_t cap) { auto in = ep.make_subscriber({topic_str}); auto fd = in.fd(); fd_set readset; @@ -178,7 +178,7 @@ void subscribe_mode_select(broker::endpoint& ep, const std::string& topic_str, #endif // BROKER_WINDOWS void subscribe_mode_stream(broker::endpoint& ep, const std::string& topic_str, - size_t cap) { + size_t cap) { auto worker = ep.subscribe( // Filter. {topic_str}, @@ -213,7 +213,7 @@ void split(std::vector& result, std::string_view str, result.emplace_back(std::string{}); } -} // namespace +} // namespace int main(int argc, char** argv) { broker::endpoint::system_guard sys_guard; @@ -265,7 +265,7 @@ int main(int argc, char** argv) { uint16_t port; try { port = static_cast(std::stoi(fields.back())); - } catch(std::exception&) { + } catch (std::exception&) { guard_type guard{cout_mtx}; std::cerr << "*** invalid port: " << fields.back() << std::endl; continue; @@ -278,32 +278,24 @@ int main(int argc, char** argv) { std::cerr << "*** invalid mode or implementation setting\n"; }; if (rate) { - auto rate_printer = std::thread{[]{ - size_t msg_count_prev = msg_count; - while (true) { - std::this_thread::sleep_for(std::chrono::seconds(1)); - size_t current = msg_count; - std::cout << current - msg_count_prev << std::endl; - msg_count_prev = current; - } + auto rate_printer = std::thread{[] { + size_t msg_count_prev = msg_count; + while (true) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + size_t current = msg_count; + std::cout << current - msg_count_prev << std::endl; + msg_count_prev = current; + } }}; rate_printer.detach(); } using mode_fun = void (*)(broker::endpoint&, const std::string&, size_t); - mode_fun fs[] = { - publish_mode_blocking, - publish_mode_select, - subscribe_mode_blocking, - subscribe_mode_select, - subscribe_mode_stream, - dummy_mode - }; + mode_fun fs[] = {publish_mode_blocking, publish_mode_select, + subscribe_mode_blocking, subscribe_mode_select, + subscribe_mode_stream, dummy_mode}; std::pair as[] = { - {"publish", "blocking"}, - {"publish", "select"}, - {"subscribe", "blocking"}, - {"subscribe", "select"}, - {"subscribe", "stream"}, + {"publish", "blocking"}, {"publish", "select"}, {"subscribe", "blocking"}, + {"subscribe", "select"}, {"subscribe", "stream"}, }; auto b = std::begin(as); auto i = std::find(b, std::end(as), std::make_pair(params.mode, params.impl)); diff --git a/src/config.hh.in b/src/config.hh.in index 6a024f6c..3b30c3be 100644 --- a/src/config.hh.in +++ b/src/config.hh.in @@ -11,27 +11,27 @@ // GCC uses __SANITIZE_ADDRESS__, Clang uses __has_feature #if defined(__SANITIZE_ADDRESS__) - #define BROKER_ASAN +# define BROKER_ASAN #endif #if defined(__has_feature) - #if __has_feature(address_sanitizer) - #define BROKER_ASAN - #endif +# if __has_feature(address_sanitizer) +# define BROKER_ASAN +# endif #endif // FreeBSD and Windows don't support LeakSanitizer #if defined(BROKER_ASAN) && !defined(__FreeBSD__) && !defined(_WIN32) - #include - #define BROKER_LSAN_CHECK(x) __lsan_do_leak_check(x) - #define BROKER_LSAN_ENABLE() __lsan_enable() - #define BROKER_LSAN_DISABLE() __lsan_disable() - #define BROKER_LSAN_IGNORE(x) __lsan_ignore_object(x) +# include +# define BROKER_LSAN_CHECK(x) __lsan_do_leak_check(x) +# define BROKER_LSAN_ENABLE() __lsan_enable() +# define BROKER_LSAN_DISABLE() __lsan_disable() +# define BROKER_LSAN_IGNORE(x) __lsan_ignore_object(x) #else - #define BROKER_LSAN_CHECK(x) - #define BROKER_LSAN_ENABLE() - #define BROKER_LSAN_DISABLE() - #define BROKER_LSAN_IGNORE(x) +# define BROKER_LSAN_CHECK(x) +# define BROKER_LSAN_ENABLE() +# define BROKER_LSAN_DISABLE() +# define BROKER_LSAN_IGNORE(x) #endif // TODO: the "proper" way of implementing the macro would be using diff --git a/src/configuration.cc b/src/configuration.cc index 3a33d355..7e7aad39 100644 --- a/src/configuration.cc +++ b/src/configuration.cc @@ -38,12 +38,12 @@ #include "broker/version.hh" #ifdef BROKER_WINDOWS -#include -#define STDOUT_FILENO 1 -#define STDERR_FILENO 2 -#define isatty _isatty +# include +# define STDOUT_FILENO 1 +# define STDERR_FILENO 2 +# define isatty _isatty #else -#include +# include #endif namespace broker { @@ -63,9 +63,9 @@ auto concat(Ts... xs) { } [[noreturn]] void throw_illegal_log_level(const char* var, const char* cstr) { - auto what - = concat("illegal value for environment variable ", var, ": '", cstr, - "' (legal values: 'trace', 'debug', 'info', 'warning', 'error')"); + auto what = + concat("illegal value for environment variable ", var, ": '", cstr, + "' (legal values: 'trace', 'debug', 'info', 'warning', 'error')"); throw std::invalid_argument(what); } @@ -233,7 +233,7 @@ void configuration::impl::init(int argc, char** argv) { return str.compare(0, 14, "--config-file=") != 0; }; auto sep = std::stable_partition(args.begin(), args.end(), predicate); - if(sep != args.end()) { + if (sep != args.end()) { args_subset.assign(std::make_move_iterator(sep), std::make_move_iterator(args.end())); args.erase(sep, args.end()); @@ -309,9 +309,8 @@ void configuration::impl::init(int argc, char** argv) { char* end = nullptr; auto value = strtol(env, &end, 10); if (errno == ERANGE || *end != '\0' || value < 0) { - auto what - = concat("invalid value for BROKER_OUTPUT_GENERATOR_FILE_CAP: ", env, - " (expected a positive integer)"); + auto what = concat("invalid value for BROKER_OUTPUT_GENERATOR_FILE_CAP: ", + env, " (expected a positive integer)"); throw std::invalid_argument(what); } set("broker.output-generator-file-cap", static_cast(value)); diff --git a/src/data.cc b/src/data.cc index 5a1fe70a..b56fac57 100644 --- a/src/data.cc +++ b/src/data.cc @@ -21,8 +21,8 @@ constexpr const char* data_type_names[] = { }; template -using data_variant_at_t - = std::variant_alternative_t(Type), data_variant>; +using data_variant_at_t = + std::variant_alternative_t(Type), data_variant>; // Make sure the static_cast in data::get_type is safe. using std::is_same_v; @@ -94,9 +94,8 @@ const char* data::get_type_name() const { namespace { template -void container_convert(Container& c, std::string& str, - const char* left, const char* right, - const char* delim = ", ") { +void container_convert(Container& c, std::string& str, const char* left, + const char* right, const char* delim = ", ") { auto first = begin(c); auto last = end(c); str += left; @@ -135,7 +134,7 @@ struct data_converter { std::string& str; }; -} // namespace +} // namespace void convert(const table::value_type& x, std::string& str) { str += to_string(x.first) + " -> " + to_string(x.second); @@ -157,7 +156,7 @@ void convert(const data& x, std::string& str) { visit(data_converter{str}, x); } -bool convert(const data& x, endpoint_id& node){ +bool convert(const data& x, endpoint_id& node) { return is(x) && convert(get(x), node); } diff --git a/src/detail/abstract_backend.cc b/src/detail/abstract_backend.cc index 38266939..62669921 100644 --- a/src/detail/abstract_backend.cc +++ b/src/detail/abstract_backend.cc @@ -1,5 +1,5 @@ -#include "broker/detail/appliers.hh" #include "broker/detail/abstract_backend.hh" +#include "broker/detail/appliers.hh" namespace broker::detail { @@ -30,7 +30,6 @@ expected abstract_backend::subtract(const data& key, const data& value, } expected abstract_backend::get(const data& key, const data& value) const { - if (auto k = get(key)) return visit(retriever{value}, *k); else diff --git a/src/detail/filesystem.cc b/src/detail/filesystem.cc index ef5adce2..75f39af9 100644 --- a/src/detail/filesystem.cc +++ b/src/detail/filesystem.cc @@ -1,29 +1,29 @@ #include "broker/detail/filesystem.hh" -#include #include #include +#include #include #include "broker/config.hh" #ifndef BROKER_WINDOWS -#include +# include #endif #ifndef BROKER_HAS_STD_FILESYSTEM -#include -#include +# include +# include -#ifdef BROKER_BSD -#include -#endif +# ifdef BROKER_BSD +# include +# endif -#include -#include +# include +# include -#include "broker/detail/die.hh" +# include "broker/detail/die.hh" namespace broker::detail { @@ -48,7 +48,7 @@ std::vector tokenize(std::string input, const std::string delim) { std::vector rval; size_t n; - while ( (n = input.find(delim)) != std::string::npos ) { + while ((n = input.find(delim)) != std::string::npos) { rval.push_back(input.substr(0, n)); input.erase(0, n + 1); } @@ -57,26 +57,25 @@ std::vector tokenize(std::string input, const std::string delim) { return rval; } -} // namespace +} // namespace bool mkdirs(const path& p) { const mode_t perms = 0777; - if ( p.empty() ) + if (p.empty()) return true; path dir_to_make = ""; - for ( auto& pc : tokenize(p, "/") ) { + for (auto& pc : tokenize(p, "/")) { dir_to_make += pc; dir_to_make += "/"; - if ( ::mkdir(dir_to_make.c_str(), perms) < 0 ) { - - if ( errno == EISDIR ) - continue; + if (::mkdir(dir_to_make.c_str(), perms) < 0) { + if (errno == EISDIR) + continue; - if ( errno == EEXIST && is_directory(dir_to_make) ) + if (errno == EEXIST && is_directory(dir_to_make)) continue; return false; @@ -89,7 +88,7 @@ bool mkdirs(const path& p) { path dirname(const path& p) { auto last_slash = p.find_last_of('/'); - if ( last_slash == path::npos ) + if (last_slash == path::npos) return ""; return p.substr(0, last_slash); @@ -110,11 +109,11 @@ std::once_flag openmax_flag; // Portable solution to retrieve the value of OPEN_MAX. // Adapted from: http://stackoverflow.com/a/8225250 long open_max() { -#ifdef OPEN_MAX +# ifdef OPEN_MAX static long openmax = OPEN_MAX; -#else +# else static long openmax = 0; -#endif +# endif std::call_once(openmax_flag, [&] { if (openmax == 0) { errno = 0; @@ -129,7 +128,7 @@ long open_max() { return openmax; } -} // namespace +} // namespace bool remove_all(const path& p) { struct stat st; @@ -175,8 +174,7 @@ std::string make_temp_file_name() { char fname[] = "/tmp/broker.test.XXXXXX"; auto fd = mkstemp(fname); if (fd == -1) { - fprintf(stderr, "Unable to create unique filename: %s.\n", - strerror(errno)); + fprintf(stderr, "Unable to create unique filename: %s.\n", strerror(errno)); exit(1); } close(fd); diff --git a/src/detail/flare.cc b/src/detail/flare.cc index dc0f6b40..17bdc5ed 100644 --- a/src/detail/flare.cc +++ b/src/detail/flare.cc @@ -16,11 +16,11 @@ #ifdef BROKER_WINDOWS -#include +# include -#define PIPE_WRITE(fd, buf, num_bytes) ::send(fd, buf, num_bytes, 0) +# define PIPE_WRITE(fd, buf, num_bytes) ::send(fd, buf, num_bytes, 0) -#define PIPE_READ(fd, buf, num_bytes) ::recv(fd, buf, num_bytes, 0) +# define PIPE_READ(fd, buf, num_bytes) ::recv(fd, buf, num_bytes, 0) namespace { @@ -38,14 +38,14 @@ bool try_again_later() { #else // BROKER_WINDOWS -#include -#include -#include -#include +# include +# include +# include +# include -#define PIPE_WRITE ::write +# define PIPE_WRITE ::write -#define PIPE_READ ::read +# define PIPE_READ ::read namespace { diff --git a/src/detail/memory_backend.cc b/src/detail/memory_backend.cc index 0af8a410..faf8a956 100644 --- a/src/detail/memory_backend.cc +++ b/src/detail/memory_backend.cc @@ -1,5 +1,5 @@ -#include #include +#include #include #include "broker/detail/appliers.hh" @@ -8,7 +8,6 @@ namespace broker { namespace detail { - memory_backend::memory_backend(backend_options opts) : options_{std::move(opts)} { // nop @@ -53,8 +52,8 @@ expected memory_backend::erase(const data& key) { } expected memory_backend::clear() { - store_.clear(); - return {}; + store_.clear(); + return {}; } expected memory_backend::expire(const data& key, timestamp ts) { @@ -76,7 +75,7 @@ expected memory_backend::get(const data& key) const { expected memory_backend::keys() const { set keys; - for ( auto i = store_.begin(); i != store_.end(); i++ ) + for (auto i = store_.begin(); i != store_.end(); i++) keys.insert(i->first); return expected(std::move(keys)); } diff --git a/src/detail/monotonic_buffer_resource.cc b/src/detail/monotonic_buffer_resource.cc index 10d5570b..b2c98b4e 100644 --- a/src/detail/monotonic_buffer_resource.cc +++ b/src/detail/monotonic_buffer_resource.cc @@ -15,8 +15,8 @@ constexpr size_t block_size = 1024; } // namespace void* monotonic_buffer_resource::allocate(size_t num_bytes, size_t alignment) { - if (auto res = std::align(alignment, num_bytes, - current_->bytes, remaining_)) { + if (auto res = std::align(alignment, num_bytes, current_->bytes, + remaining_)) { current_->bytes = static_cast(res) + num_bytes; remaining_ -= num_bytes; return res; diff --git a/src/detail/prefix_matcher.cc b/src/detail/prefix_matcher.cc index 600c417a..c2847005 100644 --- a/src/detail/prefix_matcher.cc +++ b/src/detail/prefix_matcher.cc @@ -12,4 +12,4 @@ bool prefix_matcher::operator()(const filter_type& filter, } } // namespace detail -} // namespace broker +} // namespace broker diff --git a/src/detail/sqlite_backend.cc b/src/detail/sqlite_backend.cc index 9a7f6905..c12bd1ac 100644 --- a/src/detail/sqlite_backend.cc +++ b/src/detail/sqlite_backend.cc @@ -80,8 +80,8 @@ struct sqlite_backend::impl { BROKER_TRACE(BROKER_ARG(path)); auto dir = detail::dirname(path); - if ( ! dir.empty() ) { - if ( ! detail::is_directory(dir) && ! detail::mkdirs(dir) ) { + if (!dir.empty()) { + if (!detail::is_directory(dir) && !detail::mkdirs(dir)) { return false; } } @@ -92,7 +92,8 @@ struct sqlite_backend::impl { auto result = sqlite3_open(path.c_str(), &db); BROKER_LSAN_ENABLE(); if (result != SQLITE_OK) { - BROKER_ERROR("failed to open database:" << path << ":" << sqlite3_errmsg(db)); + BROKER_ERROR("failed to open database:" << path << ":" + << sqlite3_errmsg(db)); sqlite3_close(db); db = nullptr; return false; @@ -151,7 +152,7 @@ struct sqlite_backend::impl { finalize.push_back(*stmt); return sqlite3_prepare_v2(db, sql, -1, stmt, nullptr) == SQLITE_OK; }; - for (auto& stmt: statements) + for (auto& stmt : statements) if (!prepare(stmt.first, stmt.second)) { BROKER_ERROR("failed to prepare statement:" << stmt.second); sqlite3_close(db); @@ -194,8 +195,8 @@ struct sqlite_backend::impl { return false; // Bind key. - result = sqlite3_bind_blob64(update, 3, key_blob.data(), - key_blob.size(), SQLITE_STATIC); + result = sqlite3_bind_blob64(update, 3, key_blob.data(), key_blob.size(), + SQLITE_STATIC); if (result != SQLITE_OK) return false; @@ -220,16 +221,13 @@ struct sqlite_backend::impl { std::vector finalize; }; - sqlite_backend::sqlite_backend(backend_options opts) - : impl_{std::make_unique(std::move(opts))} { -} + : impl_{std::make_unique(std::move(opts))} {} -sqlite_backend::~sqlite_backend() { -} +sqlite_backend::~sqlite_backend() {} bool sqlite_backend::init_failed() const { - return ! impl_->db; + return !impl_->db; } expected sqlite_backend::put(const data& key, data value, @@ -314,11 +312,11 @@ expected sqlite_backend::erase(const data& key) { key_blob.size(), SQLITE_STATIC); if (result != SQLITE_OK) return ec::backend_failure; - result = sqlite3_step(impl_->erase); + result = sqlite3_step(impl_->erase); if (result != SQLITE_DONE) return ec::backend_failure; - //if (sqlite3_changes(impl_->db) == 0) - // return ec::no_such_key; + // if (sqlite3_changes(impl_->db) == 0) + // return ec::no_such_key; return {}; } @@ -337,7 +335,7 @@ expected sqlite_backend::expire(const data& key, timestamp ts) { return ec::backend_failure; auto guard = make_statement_guard(impl_->expire); // Bind key. - auto [key_ok, key_blob] = to_blob(key); + auto [key_ok, key_blob] = to_blob(key); if (!key_ok) { BROKER_DEBUG("sqlite_backend::expire: to_blob(key) failed"); return ec::invalid_data; @@ -351,7 +349,7 @@ expected sqlite_backend::expire(const data& key, timestamp ts) { if (result != SQLITE_OK) return ec::backend_failure; // Execute query. - result = sqlite3_step(impl_->expire); + result = sqlite3_step(impl_->expire); if (result != SQLITE_DONE) return ec::backend_failure; return sqlite3_changes(impl_->db) == 1; @@ -401,7 +399,7 @@ expected sqlite_backend::exists(const data& key) const { if (!impl_->db) return ec::backend_failure; auto guard = make_statement_guard(impl_->exists); - auto [key_ok, key_blob] = to_blob(key); + auto [key_ok, key_blob] = to_blob(key); if (!key_ok) { BROKER_DEBUG("sqlite_backend::exists: to_blob(key) failed"); return ec::invalid_data; @@ -410,25 +408,24 @@ expected sqlite_backend::exists(const data& key) const { key_blob.size(), SQLITE_STATIC); if (result != SQLITE_OK) return ec::backend_failure; - result = sqlite3_step(impl_->exists); - if (result == SQLITE_DONE) - return false; - if (result != SQLITE_ROW) + result = sqlite3_step(impl_->exists); + if (result == SQLITE_DONE) + return false; + if (result != SQLITE_ROW) return ec::backend_failure; auto n = sqlite3_column_int(impl_->exists, 0); BROKER_ASSERT(n == 1); - return true; - + return true; } expected sqlite_backend::size() const { if (!impl_->db) return ec::backend_failure; auto guard = make_statement_guard(impl_->size); - auto result = sqlite3_step(impl_->size); - if (result != SQLITE_ROW) - return ec::backend_failure; - return sqlite3_column_int(impl_->size, 0); + auto result = sqlite3_step(impl_->size); + if (result != SQLITE_ROW) + return ec::backend_failure; + return sqlite3_column_int(impl_->size, 0); } expected sqlite_backend::snapshot() const { diff --git a/src/endpoint.cc b/src/endpoint.cc index 1d78b6f0..4b35c285 100644 --- a/src/endpoint.cc +++ b/src/endpoint.cc @@ -61,7 +61,7 @@ #include #ifdef BROKER_WINDOWS -#include "Winsock2.h" +# include "Winsock2.h" #endif using namespace std::literals; @@ -105,15 +105,14 @@ struct async_helper_state { }; template -using async_helper_actor - = caf::stateful_actor>; +using async_helper_actor = + caf::stateful_actor>; caf::actor_system_config& nat_cfg(configuration& cfg) { internal::configuration_access helper{&cfg}; return helper.cfg(); } - } // namespace // --- nested classes ---------------------------------------------------------- @@ -746,10 +745,9 @@ uint16_t endpoint::web_socket_listen(const std::string& address, uint16_t port, internal::web_socket::connect_event_t& ev) { auto& [pull, push] = ev; auto user_agent = caf::get_or(hdr, "web-socket.fields.User-Agent", "null"); - auto addr - = network_info{caf::get_or(hdr, "web-socket.remote-address", "unknown"), - caf::get_or(hdr, "web-socket.remote-port", uint16_t{0}), - 0s}; + auto addr = + network_info{caf::get_or(hdr, "web-socket.remote-address", "unknown"), + caf::get_or(hdr, "web-socket.remote-port", uint16_t{0}), 0s}; BROKER_INFO("new JSON client with address" << addr << "and user agent" << user_agent); using impl_t = internal::json_client_actor; diff --git a/src/error.cc b/src/error.cc index d2809a9a..34f39d1e 100644 --- a/src/error.cc +++ b/src/error.cc @@ -132,7 +132,8 @@ uint16_t error::category() const noexcept { const std::string* error::message() const noexcept { auto& msg = native(*this).context(); - if (auto v1 = caf::make_const_typed_message_view(msg)) + if (auto v1 = + caf::make_const_typed_message_view(msg)) return std::addressof(get<1>(v1)); else if (auto v2 = caf::make_const_typed_message_view(msg)) return std::addressof(get<0>(v2)); diff --git a/src/gateway.cc b/src/gateway.cc index c55ef290..b07286f4 100644 --- a/src/gateway.cc +++ b/src/gateway.cc @@ -64,7 +64,7 @@ void gateway::setup(const caf::actor& internal, const caf::actor& external) { caf::anon_send(external, atom::join_v, internal, filter_type{""}); } -void gateway::shutdown(){ +void gateway::shutdown() { anon_send(internal_core(), atom::shutdown_v); anon_send(external_core(), atom::shutdown_v); } diff --git a/src/internal/clone_actor.cc b/src/internal/clone_actor.cc index 047eea06..4a685261 100644 --- a/src/internal/clone_actor.cc +++ b/src/internal/clone_actor.cc @@ -48,8 +48,8 @@ clone_state::clone_state(caf::event_based_actor* ptr, endpoint_id this_endpoint, caf::async::consumer_resource in_res, caf::async::producer_resource out_res) : input(this), max_sync_interval(master_timeout) { - super::init(ptr, move(this_endpoint), ep_clock, move(nm), - move(parent), move(in_res), move(out_res)); + super::init(ptr, move(this_endpoint), ep_clock, move(nm), move(parent), + move(in_res), move(out_res)); master_topic = store_name / topic::master_suffix(); super::init(input); max_get_delay = caf::get_or(ptr->config(), "broker.store.max-get-delay", @@ -314,9 +314,10 @@ void clone_state::send(producer_type* ptr, const entity_id&, BROKER_TRACE(BROKER_ARG(what)); BROKER_DEBUG("send attach_writer_command with offset" << what.offset); auto msg = make_command_message( - master_topic, internal_command{0, id, master_id, - attach_writer_command{ - what.offset, what.heartbeat_interval}}); + master_topic, + internal_command{0, id, master_id, + attach_writer_command{what.offset, + what.heartbeat_interval}}); self->send(core, atom::publish_v, move(msg)); } @@ -452,7 +453,6 @@ void clone_state::start_output() { } } - void clone_state::send_to_master(internal_command_variant&& content) { if (output_opt) { BROKER_ASSERT(master_id); @@ -473,9 +473,8 @@ void clone_state::send_to_master(internal_command_variant&& content) { caf::behavior clone_state::make_behavior() { // Setup. self->monitor(core); - self->set_down_handler([this](const caf::down_msg& msg) { - on_down_msg(msg.source, msg.reason); - }); + self->set_down_handler( + [this](const caf::down_msg& msg) { on_down_msg(msg.source, msg.reason); }); // Ask the master to add this clone. send(std::addressof(input), clone_state::channel_type::nack{{0}}); // Schedule first tick and set a timeout for the attach operation. diff --git a/src/internal/connector.cc b/src/internal/connector.cc index 5e57f018..aad50a24 100644 --- a/src/internal/connector.cc +++ b/src/internal/connector.cc @@ -189,7 +189,7 @@ void endpoint::deinit_ssl_api() { } // namespace broker -namespace broker::internal{ +namespace broker::internal { /// Creates an SSL context for the connector. caf::net::openssl::ctx_ptr @@ -447,22 +447,22 @@ class pipe_reader { switch (msg_type) { case connector_msg::connect: { BROKER_DEBUG("received connect event"); - auto&& [eid, addr] - = from_source(src); + auto&& [eid, addr] = + from_source(src); mgr.connect(eid, addr); break; } case connector_msg::drop: { BROKER_DEBUG("received drop event"); - auto&& [eid, addr] - = from_source(src); + auto&& [eid, addr] = + from_source(src); mgr.drop(eid, addr); break; } case connector_msg::listen: { BROKER_DEBUG("received listen event"); - auto&& [eid, host, port, reuse_addr] - = from_source(src); + auto&& [eid, host, port, reuse_addr] = + from_source(src); mgr.listen(eid, host, port, reuse_addr); break; } @@ -1535,9 +1535,9 @@ bool connect_state::proceed_with_handshake(endpoint_id id, bool is_originator) { BROKER_DEBUG("detected redundant connection but " "find_pending_handshake failed"); send(wire_format::make_drop_conn_msg( - this_peer(), ec::logic_error, - "detected redundant connection but " - "find_pending_handshake failed")); + this_peer(), ec::logic_error, + "detected redundant connection but " + "find_pending_handshake failed")); transition(&connect_state::err); return false; } @@ -1874,7 +1874,6 @@ struct ssl_lib_guard { } } - ~ssl_lib_guard() { if (ssl_initialized_) endpoint::deinit_ssl_api(); diff --git a/src/internal/connector_adapter.cc b/src/internal/connector_adapter.cc index b598ef2d..5448b211 100644 --- a/src/internal/connector_adapter.cc +++ b/src/internal/connector_adapter.cc @@ -149,7 +149,7 @@ void connector_adapter::async_connect(const network_info& addr, using caf::get; using std::move; auto cb = [f{move(f)}, g{move(g)}, h{move(h)}](const caf::message& msg) { - if (auto xs1= connection_event(msg)) { + if (auto xs1 = connection_event(msg)) { f(get<0>(xs1), get<1>(xs1), get<2>(xs1), get<3>(xs1)); } else if (auto xs2 = redundant_connection_event(msg)) { g(get<0>(xs2), get<1>(xs2)); diff --git a/src/internal/core_actor.cc b/src/internal/core_actor.cc index e74bfb18..1a54cea7 100644 --- a/src/internal/core_actor.cc +++ b/src/internal/core_actor.cc @@ -66,7 +66,7 @@ core_actor_state::core_actor_state(caf::event_based_actor* self, on_peer_unavailable, filter, peer_statuses)); } - ttl = caf::get_or(self->config(),"broker.ttl", defaults::ttl); + ttl = caf::get_or(self->config(), "broker.ttl", defaults::ttl); } core_actor_state::~core_actor_state() { @@ -369,7 +369,7 @@ void core_actor_state::shutdown(shutdown_options options) { // Drop all peers. Don't cancel their flows, though. Incoming flows were // cancelled already and output flows get closed automatically once the // mergers shut down. - for (auto& kvp: peers) { + for (auto& kvp : peers) { auto& [peer_id, st] = kvp; if (!st.invalidated) { BROKER_DEBUG("drop state for" << peer_id); @@ -427,8 +427,8 @@ void core_actor_state::emit(endpoint_info ep, EnumConstant code, str = topic::statuses_str; else str = topic::errors_str; - using factory - = std::conditional_t, status, error_factory>; + using factory = + std::conditional_t, status, error_factory>; // Generate a data message from the converted content and address it to this // node only. This ensures that the data remains visible locally only. auto val = factory::make(code, std::move(ep), msg); @@ -680,27 +680,27 @@ core_actor_state::get_or_init_data_outputs() { if (!data_outputs) { BROKER_DEBUG("create data outputs"); // Hook into the central merge point. - data_outputs - = central_merge - ->as_observable() - // Drop everything but data messages and only process messages that - // are not meant for another peer. - .filter([this](const node_message& msg) { - // Note: local subscribers do not receive messages from local - // publishers. Except when the message explicitly says otherwise by - // setting receiver == id. This is the case for messages that were - // published via `(atom::publish, atom::local, ...)` message. - auto receiver = get_receiver(msg); - return get_type(msg) == packed_message_type::data - && (get_sender(msg) != id || receiver == id) - && (!receiver || receiver == id); - }) - // Deserialize payload and wrap it into an actual data message. - .flat_map_optional([this](const node_message& msg) { - return unpack(get_packed_message(msg)); - }) - // Convert this blueprint to an actual observable. - .as_observable(); + data_outputs = + central_merge + ->as_observable() + // Drop everything but data messages and only process messages that + // are not meant for another peer. + .filter([this](const node_message& msg) { + // Note: local subscribers do not receive messages from local + // publishers. Except when the message explicitly says otherwise by + // setting receiver == id. This is the case for messages that were + // published via `(atom::publish, atom::local, ...)` message. + auto receiver = get_receiver(msg); + return get_type(msg) == packed_message_type::data + && (get_sender(msg) != id || receiver == id) + && (!receiver || receiver == id); + }) + // Deserialize payload and wrap it into an actual data message. + .flat_map_optional([this](const node_message& msg) { + return unpack(get_packed_message(msg)); + }) + // Convert this blueprint to an actual observable. + .as_observable(); } return data_outputs; } @@ -710,22 +710,22 @@ core_actor_state::get_or_init_command_outputs() { if (!command_outputs) { BROKER_DEBUG("create command outputs"); // Hook into the central merge point. - command_outputs - = central_merge - ->as_observable() - // Drop everything but command messages and only process messages that - // are not meant for another peer. - .filter([this](const node_message& msg) { - auto receiver = get_receiver(msg); - return get_type(msg) == packed_message_type::command - && (!receiver || receiver == id); - }) - // Deserialize payload and wrap it into an actual command message. - .flat_map_optional([this](const node_message& msg) { - return unpack(get_packed_message(msg)); - }) - // Convert this blueprint to an actual observable. - .as_observable(); + command_outputs = + central_merge + ->as_observable() + // Drop everything but command messages and only process messages that + // are not meant for another peer. + .filter([this](const node_message& msg) { + auto receiver = get_receiver(msg); + return get_type(msg) == packed_message_type::command + && (!receiver || receiver == id); + }) + // Deserialize payload and wrap it into an actual command message. + .flat_map_optional([this](const node_message& msg) { + return unpack(get_packed_message(msg)); + }) + // Convert this blueprint to an actual observable. + .as_observable(); } return command_outputs; } @@ -969,9 +969,10 @@ caf::result core_actor_state::attach_master(const std::string& name, auto [con1, prod1] = make_spsc_buffer_resource(); auto [con2, prod2] = make_spsc_buffer_resource(); // Spin up the master and connect it to our flows. - auto hdl = self->system().spawn( - id, name, std::move(ptr), caf::actor{self}, clock, std::move(con1), - std::move(prod2)); + auto hdl = self->system().spawn(id, name, std::move(ptr), + caf::actor{self}, clock, + std::move(con1), + std::move(prod2)); filter_type filter{name / topic::master_suffix()}; subscribe(filter); get_or_init_command_outputs() diff --git a/src/internal/flare_actor.cc b/src/internal/flare_actor.cc index 6cd6f585..bbb490e6 100644 --- a/src/internal/flare_actor.cc +++ b/src/internal/flare_actor.cc @@ -11,9 +11,7 @@ namespace broker::internal { flare_actor::flare_actor(caf::actor_config& sys) - : blocking_actor{sys}, - flare_count_{0} { -} + : blocking_actor{sys}, flare_count_{0} {} void flare_actor::launch(caf::execution_unit*, bool, bool) { // Nothing todo here since we only extract messages via receive() calls. @@ -22,13 +20,13 @@ void flare_actor::launch(caf::execution_unit*, bool, bool) { void flare_actor::act() { // Usually called from launch(). But should never happen in our // implementation. - CAF_ASSERT(! "act() of flare_actor called"); + CAF_ASSERT(!"act() of flare_actor called"); } void flare_actor::await_data() { BROKER_DEBUG("awaiting data"); std::unique_lock lock{flare_mtx_}; - if (flare_count_ > 0 ) + if (flare_count_ > 0) return; lock.unlock(); flare_.await_one(); diff --git a/src/internal/generator_file_reader.cc b/src/internal/generator_file_reader.cc index 245db07f..4441c247 100644 --- a/src/internal/generator_file_reader.cc +++ b/src/internal/generator_file_reader.cc @@ -19,15 +19,15 @@ #ifdef BROKER_WINDOWS -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif // WIN32_LEAN_AND_MEAN +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif // WIN32_LEAN_AND_MEAN -#ifndef NOMINMAX -#define NOMINMAX -#endif // NOMINMAX +# ifndef NOMINMAX +# define NOMINMAX +# endif // NOMINMAX -#include +# include namespace { @@ -64,10 +64,10 @@ void* make_file_view(void* mapper, size_t file_size) { #else // BROKER_WINDOWS -#include -#include -#include -#include +# include +# include +# include +# include namespace { @@ -180,8 +180,8 @@ caf::error generator_file_reader::read_raw(read_raw_callback f) { BROKER_TRY(generator_(value)); if (!sealed_) ++data_entries_; - value_type x - = make_data_message(topic_table_[topic_id], std::move(value)); + value_type x = make_data_message(topic_table_[topic_id], + std::move(value)); auto consumed = caf::make_span(pos, source_.remainder().data()); if (!f(&x, consumed)) return caf::none; @@ -196,8 +196,8 @@ caf::error generator_file_reader::read_raw(read_raw_callback f) { BROKER_TRY(generator_(cmd)); if (!sealed_) ++command_entries_; - value_type x - = make_command_message(topic_table_[topic_id], std::move(cmd)); + value_type x = make_command_message(topic_table_[topic_id], + std::move(cmd)); auto consumed = caf::make_span(pos, source_.remainder().data()); if (!f(&x, consumed)) return caf::none; diff --git a/src/internal/generator_file_writer.cc b/src/internal/generator_file_writer.cc index e6d783a6..7e43c558 100644 --- a/src/internal/generator_file_writer.cc +++ b/src/internal/generator_file_writer.cc @@ -132,7 +132,8 @@ generator_file_writer_ptr make_generator_file_writer(const std::string& fname) { generator_file_writer& operator<<(generator_file_writer& out, const data_message& x) { if (auto err = out.write(x)) { - BROKER_ERROR("error writing data message to generator file:" << to_string(err)); + BROKER_ERROR( + "error writing data message to generator file:" << to_string(err)); } return out; } diff --git a/src/internal/json_client.cc b/src/internal/json_client.cc index ce26ea8f..f285283c 100644 --- a/src/internal/json_client.cc +++ b/src/internal/json_client.cc @@ -213,22 +213,21 @@ void json_client_state::init( auto core_json = // self->make_observable() .from_resource(core_pull2) - .map( - [this](const data_message& msg) -> caf::cow_string { - writer.reset(); - auto decorator = decorated(msg); - if (writer.apply(decorator)) { - // Serialization OK, forward message to client. - auto json = writer.str(); - auto str = std::string{json.begin(), json.end()}; - return caf::cow_string{std::move(str)}; - } else { - // Report internal error to client. - auto ctx = to_string(writer.get_error().context()); - auto str = render_error(enum_str(ec::serialization_failed), ctx); - return caf::cow_string{std::move(str)}; - } - }) + .map([this](const data_message& msg) -> caf::cow_string { + writer.reset(); + auto decorator = decorated(msg); + if (writer.apply(decorator)) { + // Serialization OK, forward message to client. + auto json = writer.str(); + auto str = std::string{json.begin(), json.end()}; + return caf::cow_string{std::move(str)}; + } else { + // Report internal error to client. + auto ctx = to_string(writer.get_error().context()); + auto str = render_error(enum_str(ec::serialization_failed), ctx); + return caf::cow_string{std::move(str)}; + } + }) .as_observable(); auto sub = caf::flow::merge(ctrl_msgs->as_observable(), core_json) // .subscribe(out); diff --git a/src/internal/master_actor.cc b/src/internal/master_actor.cc index 7414eed7..1d125d59 100644 --- a/src/internal/master_actor.cc +++ b/src/internal/master_actor.cc @@ -460,7 +460,7 @@ caf::behavior master_state::make_behavior() { BROKER_TRACE(BROKER_ARG(id) << BROKER_ARG(core) << BROKER_ARG(store_name)); // Setup. self->monitor(core); - self->set_down_handler([this](const caf::down_msg& msg) { + self->set_down_handler([this](const caf::down_msg& msg) { // on_down_msg(msg.source, msg.reason); }); // Schedule first tick. diff --git a/src/internal/master_resolver.cc b/src/internal/master_resolver.cc index 2f0ffc85..74a8c4f0 100644 --- a/src/internal/master_resolver.cc +++ b/src/internal/master_resolver.cc @@ -29,18 +29,16 @@ caf::behavior master_resolver(master_resolver_actor* self) { caf::actor& who_asked) { BROKER_DEBUG("resolver starts looking for:" << name); for (auto& peer : peers) - self->send(peer, atom::store_v, atom::master_v, - atom::get_v, name); + self->send(peer, atom::store_v, atom::master_v, atom::get_v, name); self->state.remaining_responses = peers.size(); self->state.who_asked = std::move(who_asked); }, [=](caf::actor& master) { BROKER_DEBUG("resolver found master:" << master); - self->send(self->state.who_asked, atom::master_v, - std::move(master)); + self->send(self->state.who_asked, atom::master_v, std::move(master)); self->quit(); - } + }, }; } diff --git a/src/internal/metric_collector.cc b/src/internal/metric_collector.cc index bea5d039..026df8f3 100644 --- a/src/internal/metric_collector.cc +++ b/src/internal/metric_collector.cc @@ -14,8 +14,8 @@ class remote_counter : public metric_collector::remote_metric { using super = metric_collector::remote_metric; static constexpr auto type_tag = std::is_same_v - ? ct::metric_type::int_counter - : ct::metric_type::dbl_counter; + ? ct::metric_type::int_counter + : ct::metric_type::dbl_counter; using super::super; @@ -41,8 +41,8 @@ class remote_gauge : public metric_collector::remote_metric { using super = metric_collector::remote_metric; static constexpr auto type_tag = std::is_same_v - ? ct::metric_type::int_gauge - : ct::metric_type::dbl_gauge; + ? ct::metric_type::int_gauge + : ct::metric_type::dbl_gauge; using super::super; @@ -68,8 +68,8 @@ class remote_histogram : public metric_collector::remote_metric { using super = metric_collector::remote_metric; static constexpr auto type_tag = std::is_same_v - ? ct::metric_type::int_histogram - : ct::metric_type::dbl_histogram; + ? ct::metric_type::int_histogram + : ct::metric_type::dbl_histogram; using super::super; diff --git a/src/internal/metric_exporter.cc b/src/internal/metric_exporter.cc index 3fd6988c..cd70b4ae 100644 --- a/src/internal/metric_exporter.cc +++ b/src/internal/metric_exporter.cc @@ -24,8 +24,8 @@ metric_exporter_params::from(const caf::actor_system_config& cfg) { if (result.id.empty()) result.id = result.target.suffix(); } - result.interval - = caf::get_or(*dict, "interval", defaults::metrics::export_interval); + result.interval = caf::get_or(*dict, "interval", + defaults::metrics::export_interval); if (result.interval.count() == 0) result.interval = defaults::metrics::export_interval; } diff --git a/src/internal/metric_view.cc b/src/internal/metric_view.cc index a0939a95..e8eaa94c 100644 --- a/src/internal/metric_view.cc +++ b/src/internal/metric_view.cc @@ -10,11 +10,12 @@ metric_view::metric_view(const vector* row) auto at = [row](field x) -> const auto& { return (*row)[index(x)]; }; - auto row_ok - = row != nullptr && row->size() == row_size && is(at(field::prefix)) - && is(at(field::name)) && is(at(field::type)) - && is(at(field::unit)) && is(at(field::helptext)) - && is(at(field::is_sum)) && has_properly_typed_labels(*row); + auto row_ok = row != nullptr && row->size() == row_size + && is(at(field::prefix)) && is(at(field::name)) + && is(at(field::type)) && is(at(field::unit)) + && is(at(field::helptext)) + && is(at(field::is_sum)) + && has_properly_typed_labels(*row); if (row_ok && get_type(*row, type_)) { row_ = row; } else { diff --git a/src/internal/network_cache.cc b/src/internal/network_cache.cc index c17cc6f4..77b9bbb6 100644 --- a/src/internal/network_cache.cc +++ b/src/internal/network_cache.cc @@ -28,13 +28,9 @@ void network_cache::set_use_ssl(bool use_ssl) { caf::result network_cache::fetch(const network_info& x) { auto rp = self->make_response_promise(); - fetch(x, - [=](caf::actor hdl) mutable { - rp.deliver(std::move(hdl)); - }, - [=](caf::error err) mutable { - rp.deliver(std::move(err)); - }); + fetch( + x, [=](caf::actor hdl) mutable { rp.deliver(std::move(hdl)); }, + [=](caf::error err) mutable { rp.deliver(std::move(err)); }); return rp; } diff --git a/src/internal/pending_connection.cc b/src/internal/pending_connection.cc index 87a54174..0de13fad 100644 --- a/src/internal/pending_connection.cc +++ b/src/internal/pending_connection.cc @@ -9,4 +9,3 @@ pending_connection::~pending_connection() { } } // namespace broker::internal - diff --git a/src/internal/prometheus.cc b/src/internal/prometheus.cc index 218c6b9f..2820ca00 100644 --- a/src/internal/prometheus.cc +++ b/src/internal/prometheus.cc @@ -22,20 +22,18 @@ constexpr size_t max_request_size = 512 * 1024; constexpr string_view valid_request_start = "GET /metrics HTTP/1."; // HTTP response for requests that exceed the size limit. -constexpr string_view request_too_large - = "HTTP/1.1 413 Request Entity Too Large\r\n" - "Connection: Closed\r\n\r\n"; +constexpr string_view request_too_large = + "HTTP/1.1 413 Request Entity Too Large\r\n" + "Connection: Closed\r\n\r\n"; // HTTP response for requests that don't start with "GET /metrics HTTP/1". -constexpr string_view request_not_supported - = "HTTP/1.1 501 Not Implemented\r\n" - "Connection: Closed\r\n\r\n"; +constexpr string_view request_not_supported = "HTTP/1.1 501 Not Implemented\r\n" + "Connection: Closed\r\n\r\n"; // HTTP header when sending a payload. -constexpr string_view request_ok - = "HTTP/1.1 200 OK\r\n" - "Content-Type: text/plain\r\n" - "Connection: Closed\r\n\r\n"; +constexpr string_view request_ok = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Connection: Closed\r\n\r\n"; } // namespace @@ -93,8 +91,8 @@ caf::behavior prometheus_actor::make_behavior() { return; } req.insert(req.end(), msg.buf.begin(), msg.buf.end()); - auto req_str - = string_view{reinterpret_cast(req.data()), req.size()}; + auto req_str = string_view{reinterpret_cast(req.data()), + req.size()}; // Stop here if the first header line isn't complete yet. if (req_str.size() < valid_request_start.size()) return; diff --git a/src/internal/scoped_flare_actor.cc b/src/internal/scoped_flare_actor.cc index 2b588570..59e01437 100644 --- a/src/internal/scoped_flare_actor.cc +++ b/src/internal/scoped_flare_actor.cc @@ -5,15 +5,16 @@ namespace broker::internal { scoped_flare_actor::scoped_flare_actor(caf::actor_system& sys) : context_{&sys} { caf::actor_config cfg{&context_}; - self_ = caf::make_actor( - sys.next_actor_id(), sys.node(), &sys, cfg); + self_ = + caf::make_actor(sys.next_actor_id(), + sys.node(), &sys, cfg); ptr()->is_registered(true); } scoped_flare_actor::~scoped_flare_actor() { - if (! self_) + if (!self_) return; - if (! ptr()->is_terminated()) + if (!ptr()->is_terminated()) ptr()->cleanup(caf::exit_reason::normal, &context_); } diff --git a/src/internal/web_socket.cc b/src/internal/web_socket.cc index 005ece33..44bebc76 100644 --- a/src/internal/web_socket.cc +++ b/src/internal/web_socket.cc @@ -69,9 +69,9 @@ class acceptor_factory { caf::net::socket_manager_ptr make(Socket fd, caf::net::multiplexer* mpx) { using trait_t = caf::detail::ws_accept_trait; using value_type = typename trait_t::value_type; - using app_t - = caf::net::message_flow_bridge; + using app_t = + caf::net::message_flow_bridge; using caf::net::openssl_transport; using stack_t = openssl_transport>; auto policy = caf::net::openssl::policy::make(ctx_, fd); @@ -133,24 +133,24 @@ expected launch(caf::actor_system& sys, openssl_options_ptr ssl_cfg, // Callback for connecting the flows. using consumer_res_t = caf::async::consumer_resource; using producer_res_t = caf::async::producer_resource; - using res_t - = caf::expected>; - auto on_request - = [cb = std::move(on_connect), allowed_path](const caf::settings& hdr) { - auto path = caf::get_or(hdr, "web-socket.path", ""); - if (path == allowed_path) { - using caf::async::make_spsc_buffer_resource; - auto [pull1, push1] = make_spsc_buffer_resource(); - auto [pull2, push2] = make_spsc_buffer_resource(); - connect_event_t ev{std::move(pull2), std::move(push1)}; - cb(hdr, ev); - return res_t{std::make_tuple(pull1, push2, trait_t{})}; - } else { - BROKER_INFO("rejected JSON client on invalid path" << path); - return res_t{caf::make_error(caf::sec::invalid_argument, - "invalid path; try " + allowed_path)}; - } - }; + using res_t = + caf::expected>; + auto on_request = [cb = std::move(on_connect), + allowed_path](const caf::settings& hdr) { + auto path = caf::get_or(hdr, "web-socket.path", ""); + if (path == allowed_path) { + using caf::async::make_spsc_buffer_resource; + auto [pull1, push1] = make_spsc_buffer_resource(); + auto [pull2, push2] = make_spsc_buffer_resource(); + connect_event_t ev{std::move(pull2), std::move(push1)}; + cb(hdr, ev); + return res_t{std::make_tuple(pull1, push2, trait_t{})}; + } else { + BROKER_INFO("rejected JSON client on invalid path" << path); + return res_t{caf::make_error(caf::sec::invalid_argument, + "invalid path; try " + allowed_path)}; + } + }; // Launch the WebSocket and dispatch to on_connect. namespace ws = caf::net::web_socket; if (auto ctx = ssl_context_from_cfg(ssl_cfg)) { diff --git a/src/message.cc b/src/message.cc index efe54a5a..ef3f426c 100644 --- a/src/message.cc +++ b/src/message.cc @@ -10,18 +10,9 @@ using namespace std::literals; namespace broker { constexpr std::string_view p2p_message_type_names[] = { - "invalid", - "data", - "command", - "routing_update", - "ping", - "pong", - "hello", - "probe", - "version_select", - "drop_conn", - "originator_syn", - "responder_syn_ack", + "invalid", "data", "command", "routing_update", + "ping", "pong", "hello", "probe", + "version_select", "drop_conn", "originator_syn", "responder_syn_ack", "originator_ack", }; @@ -68,7 +59,7 @@ bool from_string(std::string_view str, packed_message_type& x) { } } -bool from_integer(uint8_t val, packed_message_type& x){ +bool from_integer(uint8_t val, packed_message_type& x) { if (val <= 0x04) { auto tmp = p2p_message_type{0}; if (from_integer(val, tmp)) { diff --git a/src/network_info.cc b/src/network_info.cc index 7e8b552c..f26d8107 100644 --- a/src/network_info.cc +++ b/src/network_info.cc @@ -13,8 +13,7 @@ namespace broker { network_info::network_info(std::string addr, uint16_t port, timeout::seconds retry) - : address{std::move(addr)}, port{port}, retry{retry} { -} + : address{std::move(addr)}, port{port}, retry{retry} {} bool operator==(const network_info& x, const network_info& y) { return x.address == y.address && x.port == y.port; diff --git a/src/port.cc b/src/port.cc index 56240a67..866f15bb 100644 --- a/src/port.cc +++ b/src/port.cc @@ -11,11 +11,9 @@ namespace broker { -port::port() : num_{0}, proto_{protocol::unknown} { -} +port::port() : num_{0}, proto_{protocol::unknown} {} -port::port(number_type n, protocol p) : num_{n}, proto_{p} { -} +port::port(number_type n, protocol p) : num_{n}, proto_{p} {} port::number_type port::number() const { return num_; diff --git a/src/publisher.cc b/src/publisher.cc index afb0c16c..014852bc 100644 --- a/src/publisher.cc +++ b/src/publisher.cc @@ -80,7 +80,7 @@ struct publisher_queue : public caf::ref_counted, public caf::async::producer { deref(); } - size_t demand() const noexcept{ + size_t demand() const noexcept { guard_type guard{mtx_}; return demand_; } diff --git a/src/status_subscriber.cc b/src/status_subscriber.cc index b59261d0..6e44fd25 100644 --- a/src/status_subscriber.cc +++ b/src/status_subscriber.cc @@ -2,8 +2,8 @@ #include -#include #include +#include #include "broker/endpoint.hh" #include "broker/internal/logger.hh" @@ -92,9 +92,8 @@ std::vector status_subscriber::poll() { } void status_subscriber::append_converted(std::vector& result, - const data_message& msg) { - BROKER_APPEND_CONVERTED_MSG() -} + const data_message& msg){ + BROKER_APPEND_CONVERTED_MSG()} value_type status_subscriber::convert(const data_message& msg) { BROKER_RETURN_CONVERTED_MSG() diff --git a/src/store.cc b/src/store.cc index 64c86978..5ebd597d 100644 --- a/src/store.cc +++ b/src/store.cc @@ -188,8 +188,8 @@ store::store(endpoint_id this_peer, worker frontend, std::string name) { return; } auto hdl = native(frontend); - detail::shared_store_state_ptr ptr - = std::make_shared(this_peer, std::move(name), hdl); + detail::shared_store_state_ptr ptr = + std::make_shared(this_peer, std::move(name), hdl); state_ = ptr; caf::anon_send(hdl, atom::increment_v, std::move(ptr)); } @@ -407,25 +407,28 @@ void store::put(data key, data value, std::optional expiry) { void store::erase(data key) { with_state([&](state_impl& st) { - st.anon_send(atom::local_v, internal_command_variant{erase_command{ - std::move(key), st.frontend_id()}}); + st.anon_send(atom::local_v, + internal_command_variant{ + erase_command{std::move(key), st.frontend_id()}}); }); } void store::add(data key, data value, data::type init_type, std::optional expiry) { with_state([&](state_impl& st) { - st.anon_send(atom::local_v, internal_command_variant{add_command{ - std::move(key), std::move(value), init_type, - expiry, st.frontend_id()}}); + st.anon_send(atom::local_v, + internal_command_variant{ + add_command{std::move(key), std::move(value), init_type, + expiry, st.frontend_id()}}); }); } void store::subtract(data key, data value, std::optional expiry) { with_state([&](state_impl& st) { - st.anon_send(atom::local_v, internal_command_variant{subtract_command{ - std::move(key), std::move(value), expiry, - st.frontend_id()}}); + st.anon_send(atom::local_v, + internal_command_variant{ + subtract_command{std::move(key), std::move(value), expiry, + st.frontend_id()}}); }); } diff --git a/src/store_event.cc b/src/store_event.cc index fa1d83b5..4f9209c2 100644 --- a/src/store_event.cc +++ b/src/store_event.cc @@ -31,41 +31,37 @@ std::string opt_to_string(const std::optional& x) { } // namespace store_event::insert store_event::insert::make(const vector& xs) noexcept { - return insert{xs.size() == 7 - && to(xs[0]) == store_event::type::insert - && is(xs[1]) - && (is(xs[4]) || is(xs[4])) - && is_entity_id(xs, 5, 6) - ? &xs - : nullptr}; + return insert{ + xs.size() == 7 && to(xs[0]) == store_event::type::insert + && is(xs[1]) && (is(xs[4]) || is(xs[4])) + && is_entity_id(xs, 5, 6) + ? &xs + : nullptr}; } store_event::update store_event::update::make(const vector& xs) noexcept { - return update{xs.size() == 8 - && to(xs[0]) == store_event::type::update - && is(xs[1]) - && (is(xs[5]) || is(xs[5])) - && is_entity_id(xs, 6, 7) - ? &xs - : nullptr}; + return update{ + xs.size() == 8 && to(xs[0]) == store_event::type::update + && is(xs[1]) && (is(xs[5]) || is(xs[5])) + && is_entity_id(xs, 6, 7) + ? &xs + : nullptr}; } store_event::erase store_event::erase::make(const vector& xs) noexcept { return erase{xs.size() == 5 - && to(xs[0]) == store_event::type::erase - && is(xs[1]) - && is_entity_id(xs, 3, 4) - ? &xs - : nullptr}; + && to(xs[0]) == store_event::type::erase + && is(xs[1]) && is_entity_id(xs, 3, 4) + ? &xs + : nullptr}; } store_event::expire store_event::expire::make(const vector& xs) noexcept { return expire{xs.size() == 5 - && to(xs[0]) == store_event::type::expire - && is(xs[1]) - && is_entity_id(xs, 3, 4) - ? &xs - : nullptr}; + && to(xs[0]) == store_event::type::expire + && is(xs[1]) && is_entity_id(xs, 3, 4) + ? &xs + : nullptr}; } const char* to_string(store_event::type code) noexcept { @@ -126,7 +122,7 @@ std::string to_string(const store_event::erase& x) { return result; } -bool convert(const std::string& src, store_event::type& dst) noexcept{ +bool convert(const std::string& src, store_event::type& dst) noexcept { auto begin = std::begin(type_strings); auto end = std::end(type_strings); auto i = std::find(begin, end, src); @@ -138,7 +134,7 @@ bool convert(const std::string& src, store_event::type& dst) noexcept{ return false; } -bool convert(const data& src, store_event::type& dst) noexcept{ +bool convert(const data& src, store_event::type& dst) noexcept { if (auto str = get_if(src)) return convert(*str, dst); return false; diff --git a/src/subnet.cc b/src/subnet.cc index 4b7ab5a1..5223b906 100644 --- a/src/subnet.cc +++ b/src/subnet.cc @@ -1,8 +1,8 @@ -#include #include #include #include #include +#include #include @@ -11,8 +11,7 @@ namespace broker { -subnet::subnet() : len_(0) { -} +subnet::subnet() : len_(0) {} subnet::subnet(address addr, uint8_t length) : net_(std::move(addr)), len_(length) { diff --git a/src/telemetry/histogram.cc b/src/telemetry/histogram.cc index 0ed4bd77..6eae95ec 100644 --- a/src/telemetry/histogram.cc +++ b/src/telemetry/histogram.cc @@ -54,9 +54,9 @@ double count_at(const dbl_histogram_hdl* hdl, size_t index) noexcept { } double upper_bound_at(const dbl_histogram_hdl* hdl, size_t index) noexcept { - auto xs = deref(hdl).buckets(); - BROKER_ASSERT(index < xs.size()); - return xs[index].upper_bound; + auto xs = deref(hdl).buckets(); + BROKER_ASSERT(index < xs.size()); + return xs[index].upper_bound; } dbl_histogram_hdl* dbl_histogram_get_or_add(metric_family_hdl* hdl, @@ -87,9 +87,9 @@ int64_t count_at(const int_histogram_hdl* hdl, size_t index) noexcept { } int64_t upper_bound_at(const int_histogram_hdl* hdl, size_t index) noexcept { - auto xs = deref(hdl).buckets(); - BROKER_ASSERT(index < xs.size()); - return xs[index].upper_bound; + auto xs = deref(hdl).buckets(); + BROKER_ASSERT(index < xs.size()); + return xs[index].upper_bound; } int_histogram_hdl* int_histogram_get_or_add(metric_family_hdl* hdl, diff --git a/src/telemetry/metric_registry.cc b/src/telemetry/metric_registry.cc index 3796087c..e1c1837c 100644 --- a/src/telemetry/metric_registry.cc +++ b/src/telemetry/metric_registry.cc @@ -32,9 +32,9 @@ int_counter_fam(metric_registry_impl* impl, std::string_view pre, } dbl_counter_family_hdl* -dbl_counter_fam(metric_registry_impl*impl, std::string_view pre, +dbl_counter_fam(metric_registry_impl* impl, std::string_view pre, std::string_view name, span labels, - std::string_view helptext, std::string_view unit, bool is_sum){ + std::string_view helptext, std::string_view unit, bool is_sum) { return impl->dbl_counter_fam(pre, name, labels, helptext, unit, is_sum); } @@ -87,8 +87,7 @@ metric_registry::metric_registry(metric_registry&& other) noexcept } metric_registry::metric_registry(const metric_registry& other) noexcept - : metric_registry(other.impl_, true) { -} + : metric_registry(other.impl_, true) {} metric_registry& metric_registry::operator=(metric_registry&& other) noexcept { std::swap(impl_, other.impl_); @@ -148,11 +147,11 @@ class impl_base : public metric_registry_impl { } int_counter_family_hdl* int_counter_fam(std::string_view pre, - std::string_view name, - span labels, - std::string_view helptext, - std::string_view unit, - bool is_sum) override { + std::string_view name, + span labels, + std::string_view helptext, + std::string_view unit, + bool is_sum) override { return internal::with_native_labels(labels, [=](auto xs) { auto ptr = reg_->counter_family(pre, name, xs, helptext, unit, is_sum); return reinterpret_cast(ptr); @@ -166,8 +165,8 @@ class impl_base : public metric_registry_impl { std::string_view unit, bool is_sum) override { return internal::with_native_labels(labels, [=](auto xs) { - auto ptr = reg_->counter_family(pre, name, xs, helptext, - unit, is_sum); + auto ptr = reg_->counter_family(pre, name, xs, helptext, unit, + is_sum); return reinterpret_cast(ptr); }); } @@ -187,8 +186,8 @@ class impl_base : public metric_registry_impl { span labels, std::string_view helptext, std::string_view unit, bool is_sum) override { return internal::with_native_labels(labels, [=](auto xs) { - auto ptr = reg_->gauge_family(pre, name, xs, helptext, - unit, is_sum); + auto ptr = reg_->gauge_family(pre, name, xs, helptext, unit, + is_sum); return reinterpret_cast(ptr); }); } @@ -200,8 +199,8 @@ class impl_base : public metric_registry_impl { std::string_view unit, bool is_sum) override { return internal::with_native_labels(labels, [=](auto xs) { auto bounds = caf::span{ubounds.data(), ubounds.size()}; - auto ptr = reg_->histogram_family(pre, name, xs, bounds, helptext, - unit, is_sum); + auto ptr = reg_->histogram_family(pre, name, xs, bounds, helptext, unit, + is_sum); return reinterpret_cast(ptr); }); } diff --git a/src/time.cc b/src/time.cc index e41f9bea..cba7367e 100644 --- a/src/time.cc +++ b/src/time.cc @@ -23,7 +23,8 @@ void convert(timestamp t, std::string& str) { } void convert(timestamp t, double& secs) { - secs = std::chrono::duration_cast(t.time_since_epoch()).count(); + secs = std::chrono::duration_cast(t.time_since_epoch()) + .count(); } void convert(double secs, timespan& s) { diff --git a/src/topic.cc b/src/topic.cc index 03f5e850..eb2149e6 100644 --- a/src/topic.cc +++ b/src/topic.cc @@ -13,7 +13,7 @@ std::vector topic::split(const topic& t) { ++i; continue; } - if (j == std::string::npos) { + if (j == std::string::npos) { result.push_back(t.str_.substr(i)); break; } @@ -114,6 +114,6 @@ topic topic::store_events() { } // namespace broker -broker::topic operator "" _t(const char* str, size_t len) { +broker::topic operator"" _t(const char* str, size_t len) { return broker::topic{std::string{str, len}}; } diff --git a/src/version.cc b/src/version.cc index d08cdafd..3aa3821d 100644 --- a/src/version.cc +++ b/src/version.cc @@ -6,7 +6,7 @@ namespace version { std::string string() { using std::to_string; return to_string(version::major) + '.' + to_string(version::minor) + '.' - + to_string(version::patch) + version::suffix; + + to_string(version::patch) + version::suffix; } } // namespace version diff --git a/src/worker.cc b/src/worker.cc index 8bf33286..cc3e5230 100644 --- a/src/worker.cc +++ b/src/worker.cc @@ -30,8 +30,8 @@ worker::worker(const worker& other) noexcept { new (obj_) native_t(native(other)); } -worker::worker(const impl* ptr) noexcept { - if(ptr) +worker::worker(const impl* ptr) noexcept { + if (ptr) new (obj_) native_t(native(ptr)); else new (obj_) native_t(); diff --git a/tests/benchmark/broker-benchmark.cc b/tests/benchmark/broker-benchmark.cc index 2a5515fa..5360e55b 100644 --- a/tests/benchmark/broker-benchmark.cc +++ b/tests/benchmark/broker-benchmark.cc @@ -22,10 +22,10 @@ #include "broker/zeek.hh" #ifndef BROKER_WINDOWS -# include +# include # include +# include # include -# include #endif // BROKER_WINDOWS using namespace broker; @@ -72,83 +72,77 @@ double current_time() { } static std::string random_string(int n) { - static unsigned int i = 0; - const char charset[] = - "0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; - - const size_t max_index = (sizeof(charset) - 1); - char buffer[11]; - for ( unsigned int j = 0; j < sizeof(buffer) - 1; j++ ) + static unsigned int i = 0; + const char charset[] = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"; + + const size_t max_index = (sizeof(charset) - 1); + char buffer[11]; + for (unsigned int j = 0; j < sizeof(buffer) - 1; j++) buffer[j] = charset[++i % max_index]; - buffer[sizeof(buffer) - 1] = '\0'; + buffer[sizeof(buffer) - 1] = '\0'; - return buffer; + return buffer; } static uint64_t random_count() { - static uint64_t i = 0; - return ++i; + static uint64_t i = 0; + return ++i; } vector createEventArgs() { - switch ( event_type ) { - case 1: { - return std::vector{42, "test"}; - } - - case 2: { - // This resembles a line in conn.log. - address a1; - address a2; - convert("1.2.3.4", a1); - convert("3.4.5.6", a2); - - return vector{ - now(), - random_string(10), - vector{ - a1, - port(4567, port::protocol::tcp), - a2, - port(80, port::protocol::tcp) - }, - enum_value("tcp"), - random_string(10), - std::chrono::duration_cast(std::chrono::duration(3.14)), - random_count(), - random_count(), - random_string(5), - true, - false, - random_count(), - random_string(10), - random_count(), - random_count(), - random_count(), - random_count(), - set({random_string(10), random_string(10)}) - }; - } - - case 3: { - table m; - - for ( int i = 0; i < 100; i++ ) { - set s; - for ( int j = 0; j < 10; j++ ) - s.insert(random_string(5)); - m[random_string(15)] = s; - } - - return vector{now(), m}; - } - - default: - std::cerr << "invalid event type\n"; - abort(); + switch (event_type) { + case 1: { + return std::vector{42, "test"}; + } + + case 2: { + // This resembles a line in conn.log. + address a1; + address a2; + convert("1.2.3.4", a1); + convert("3.4.5.6", a2); + + return vector{now(), + random_string(10), + vector{a1, port(4567, port::protocol::tcp), a2, + port(80, port::protocol::tcp)}, + enum_value("tcp"), + random_string(10), + std::chrono::duration_cast( + std::chrono::duration(3.14)), + random_count(), + random_count(), + random_string(5), + true, + false, + random_count(), + random_string(10), + random_count(), + random_count(), + random_count(), + random_count(), + set({random_string(10), random_string(10)})}; + } + + case 3: { + table m; + + for (int i = 0; i < 100; i++) { + set s; + for (int j = 0; j < 10; j++) + s.insert(random_string(5)); + m[random_string(15)] = s; + } + + return vector{now(), m}; } + + default: + std::cerr << "invalid event type\n"; + abort(); + } } void send_batch(endpoint& ep, publisher& p) { @@ -228,7 +222,6 @@ void receivedStats(endpoint& ep, const data& x) { static int max_exceeded_counter = 0; if (max_in_flight && in_flight > max_in_flight) { - if (++max_exceeded_counter >= 5) { std::cerr << "max-in-flight exceeded for 5 subsequent batches\n"; exit(1); diff --git a/tests/benchmark/broker-cluster-benchmark.cc b/tests/benchmark/broker-cluster-benchmark.cc index d43dc53d..b23b78a8 100644 --- a/tests/benchmark/broker-cluster-benchmark.cc +++ b/tests/benchmark/broker-cluster-benchmark.cc @@ -164,7 +164,7 @@ void println(Ts&&... xs) { namespace { -std::string trim(std::string x){ +std::string trim(std::string x) { auto predicate = [](int ch) { return !std::isspace(ch); }; x.erase(x.begin(), std::find_if(x.begin(), x.end(), predicate)); x.erase(std::find_if(x.rbegin(), x.rend(), predicate).base(), x.end()); @@ -539,9 +539,9 @@ caf::behavior consumer(caf::stateful_actor* self, caf::after(std::chrono::seconds(1)) >> [=]() mutable { if (last_printed_count != self->state.received) { - verbose::println( - this_node->name, - " received nothing for 1s, last count: ", self->state.received); + verbose::println(this_node->name, + " received nothing for 1s, last count: ", + self->state.received); last_printed_count = self->state.received; } }, @@ -660,12 +660,8 @@ caf::behavior node_manager(node_manager_actor* self, node* this_node) { verbose::println(this_node->name, " up and running"); return atom::ok_v; }, - [=](atom::read, caf::actor observer) { - run_receive_mode(self, observer); - }, - [=](atom::write, caf::actor observer) { - run_send_mode(self, observer); - }, + [=](atom::read, caf::actor observer) { run_receive_mode(self, observer); }, + [=](atom::write, caf::actor observer) { run_send_mode(self, observer); }, [=](atom::shutdown) -> caf::result { for (auto& child : self->state.children) self->send_exit(child, caf::exit_reason::user_shutdown); @@ -759,11 +755,7 @@ bool verify_node_tree(std::vector& nodes) { int generate_config(string_list directories) { constexpr const char* required_files[] = { - "/id.txt", - "/messages.dat", - "/peers.txt", - "/topics.txt", - "/broker.conf", + "/id.txt", "/messages.dat", "/peers.txt", "/topics.txt", "/broker.conf", }; // Make sure we always produce a stable config file that does not depend on // argument ordering. @@ -842,8 +834,8 @@ int generate_config(string_list directories) { if (auto val = caf::get_if(std::addressof(*conf), "broker.forward")) node.disable_forwarding = !*val; else - node.disable_forwarding - = caf::get_or(*conf, "broker.disable-forwarding", false); + node.disable_forwarding = + caf::get_or(*conf, "broker.disable-forwarding", false); } else { err::println("unable to parse ", quoted{conf_file}, ": ", to_string(conf.error())); @@ -878,7 +870,8 @@ int generate_config(string_list directories) { using output_map = std::map; std::map outputs; for (const auto& node : nodes) { - auto gptr = broker::internal::make_generator_file_reader(node.generator_file); + auto gptr = + broker::internal::make_generator_file_reader(node.generator_file); if (gptr == nullptr) { err::println("unable to open generator file: ", node.generator_file); return EXIT_FAILURE; @@ -918,8 +911,8 @@ int generate_config(string_list directories) { using walk_fun = std::function(const node&)>; walk_fun walk_left = [](const node& n) { return n.left; }; walk_fun walk_right = [](const node& n) { return n.right; }; - using traverse_t - = void(node&, node&, const output_map&, const filter&, walk_fun); + using traverse_t = void(node&, node&, const output_map&, const filter&, + walk_fun); std::function traverse; traverse = [&](node& src, node& dst, const output_map& out, const filter& f, walk_fun walk) { @@ -1048,7 +1041,7 @@ int shrink_generator_file(string_list args) { size_t new_size; try { new_size = std::stoul(args[2]); - } catch (std::exception&ex) { + } catch (std::exception& ex) { err::println("unable to parse NEW_SIZE argument: ", ex.what()); err::println("expected three positional arguments: INPUT OUTPUT NEW_SIZE"); return EXIT_FAILURE; @@ -1214,7 +1207,7 @@ int main(int argc, char** argv) { if (is_data_message(x)) ++data_entries; else - ++ command_entries; + ++command_entries; entries_by_topic[get_topic(x)] += 1; } out::println(file_name); @@ -1311,9 +1304,7 @@ int main(int argc, char** argv) { [](atom::ack) { // All is well. }, - [&](caf::error& err) { - throw std::move(err); - }); + [&](caf::error& err) { throw std::move(err); }); }; auto wait_for_ok_messages = [&](size_t num) { size_t i = 0; diff --git a/tests/benchmark/broker-fan-out.cc b/tests/benchmark/broker-fan-out.cc index efc83a26..cb0c3029 100644 --- a/tests/benchmark/broker-fan-out.cc +++ b/tests/benchmark/broker-fan-out.cc @@ -50,15 +50,15 @@ constexpr uint64_t default_message_count = 10'000'000; constexpr uint64_t default_payload_size = 1'000; std::string_view tty_codes[] = { - "\033[0m", // reset - "\033[30m", // black - "\033[31m", // red - "\033[32m", // green - "\033[33m", // yellow - "\033[34m", // blue - "\033[35m", // magenta - "\033[36m", // cyan - "\033[37m", // white + "\033[0m", // reset + "\033[30m", // black + "\033[31m", // red + "\033[32m", // green + "\033[33m", // yellow + "\033[34m", // blue + "\033[35m", // magenta + "\033[36m", // cyan + "\033[37m", // white }; } // namespace diff --git a/tests/btest/store/put-unique.cc b/tests/btest/store/put-unique.cc index 61e7c938..fe456c52 100644 --- a/tests/btest/store/put-unique.cc +++ b/tests/btest/store/put-unique.cc @@ -163,7 +163,7 @@ void clone_mode(endpoint& ep, std::vector cl_ports) { int main(int argc, char** argv) { broker::endpoint::system_guard sys_guard; // Initialize global state. - setvbuf(stdout, NULL, _IOLBF, 0); // Always line-buffer stdout. + setvbuf(stdout, NULL, _IOLBF, 0); // Always line-buffer stdout. // Parse CLI parameters using our config. broker::configuration cfg{broker::skip_init}; extend_config(cfg); diff --git a/tests/cpp/alm/multipath.cc b/tests/cpp/alm/multipath.cc index 70711008..57dfb750 100644 --- a/tests/cpp/alm/multipath.cc +++ b/tests/cpp/alm/multipath.cc @@ -139,7 +139,7 @@ TEST(multipaths are serializable) { multipath copy; MESSAGE("deserializers a copy from the path from the buffer"); { - caf::binary_deserializer source{sys,buf}; + caf::binary_deserializer source{sys, buf}; CHECK(source.apply(copy)); } MESSAGE("after a serialization roundtrip, the path is equal to its copy"); @@ -189,7 +189,7 @@ TEST(source routing extracts multipaths from routing tables) { alm::multipath::generate(ls('B', 'D'), tbl, paths, unreachables); REQUIRE_EQUAL(paths.size(), 1u); REQUIRE_EQUAL(unreachables.size(), 0u); - CHECK_EQUAL(stringify(paths[0]),"(B, [(D)])"); + CHECK_EQUAL(stringify(paths[0]), "(B, [(D)])"); } MESSAGE("Sending to E and I creates two multipaths"); { @@ -198,8 +198,8 @@ TEST(source routing extracts multipaths from routing tables) { alm::multipath::generate(ls('E', 'I'), tbl, paths, unreachables); REQUIRE_EQUAL(paths.size(), 2u); REQUIRE_EQUAL(unreachables.size(), 0u); - CHECK_EQUAL(stringify(paths[0]),"(B, [(E)])"); - CHECK_EQUAL(stringify(paths[1]),"(J, [(I)])"); + CHECK_EQUAL(stringify(paths[0]), "(B, [(E)])"); + CHECK_EQUAL(stringify(paths[1]), "(J, [(I)])"); } MESSAGE("Sending to D, E and I creates two multipaths"); { @@ -208,8 +208,8 @@ TEST(source routing extracts multipaths from routing tables) { alm::multipath::generate(ls('D', 'E', 'I'), tbl, paths, unreachables); REQUIRE_EQUAL(paths.size(), 2u); REQUIRE_EQUAL(unreachables.size(), 0u); - CHECK_EQUAL(stringify(paths[0]),"(B, [(D), (E)])"); - CHECK_EQUAL(stringify(paths[1]),"(J, [(I)])"); + CHECK_EQUAL(stringify(paths[0]), "(B, [(D), (E)])"); + CHECK_EQUAL(stringify(paths[1]), "(J, [(I)])"); } MESSAGE("Sending to B and G creates one path and one unreachable"); { @@ -218,7 +218,7 @@ TEST(source routing extracts multipaths from routing tables) { alm::multipath::generate(ls('B', 'G'), tbl, paths, unreachables); REQUIRE_EQUAL(paths.size(), 1u); REQUIRE_EQUAL(unreachables.size(), 1u); - CHECK_EQUAL(stringify(paths[0]),"(B)"); + CHECK_EQUAL(stringify(paths[0]), "(B)"); CHECK_EQUAL(unreachables, ls('G')); } } diff --git a/tests/cpp/alm/routing_table.cc b/tests/cpp/alm/routing_table.cc index b87f5a4e..af97cb81 100644 --- a/tests/cpp/alm/routing_table.cc +++ b/tests/cpp/alm/routing_table.cc @@ -220,11 +220,11 @@ TEST(inseting into revocationss creates a sorted list) { CHECK(not emplace(B, 7_lt, A).second); MESSAGE("the final list is sorted on revoker, ts, hop"); CHECK_EQUAL(lst, revocations({{A, 1_lt, B}, - {A, 2_lt, C}, - {A, 3_lt, B}, - {B, 7_lt, A}, - {C, 1_lt, A}, - {C, 2_lt, A}})); + {A, 2_lt, C}, + {A, 3_lt, B}, + {B, 7_lt, A}, + {C, 1_lt, A}, + {C, 2_lt, A}})); MESSAGE("equal_range allows access to subranges by revoker"); CHECK_EQUAL(to_revocations(equal_range(lst, A)), revocations({{A, 1_lt, B}, {A, 2_lt, C}, {A, 3_lt, B}})); diff --git a/tests/cpp/backend.cc b/tests/cpp/backend.cc index 95649242..8f8fe944 100644 --- a/tests/cpp/backend.cc +++ b/tests/cpp/backend.cc @@ -58,109 +58,75 @@ class meta_backend : public detail::abstract_backend { expected put(const data& key, data value, std::optional expiry) override { - return perform( - [&](detail::abstract_backend& backend) { - return backend.put(key, value, expiry); - } - ); + return perform([&](detail::abstract_backend& backend) { + return backend.put(key, value, expiry); + }); } expected add(const data& key, const data& value, data::type init_type, std::optional expiry) override { - return perform( - [&](detail::abstract_backend& backend) { - return backend.add(key, value, init_type, expiry); - } - ); + return perform([&](detail::abstract_backend& backend) { + return backend.add(key, value, init_type, expiry); + }); } expected subtract(const data& key, const data& value, - std::optional expiry) override { - return perform( - [&](detail::abstract_backend& backend) { - return backend.subtract(key, value, expiry); - } - ); + std::optional expiry) override { + return perform([&](detail::abstract_backend& backend) { + return backend.subtract(key, value, expiry); + }); } expected erase(const data& key) override { return perform( - [&](detail::abstract_backend& backend) { - return backend.erase(key); - } - ); + [&](detail::abstract_backend& backend) { return backend.erase(key); }); } expected clear() override { return perform( - [&](detail::abstract_backend& backend) { - return backend.clear(); - } - ); + [&](detail::abstract_backend& backend) { return backend.clear(); }); } expected expire(const data& key, timestamp ts) override { - return perform( - [&](detail::abstract_backend& backend) { - return backend.expire(key, ts); - } - ); + return perform([&](detail::abstract_backend& backend) { + return backend.expire(key, ts); + }); } expected get(const data& key) const override { return perform( - [&](detail::abstract_backend& backend) { - return backend.get(key); - } - ); + [&](detail::abstract_backend& backend) { return backend.get(key); }); } expected get(const data& key, const data& value) const override { - return perform( - [&](detail::abstract_backend& backend) { - return backend.get(key, value); - } - ); + return perform([&](detail::abstract_backend& backend) { + return backend.get(key, value); + }); } expected keys() const override { return perform( - [&](detail::abstract_backend& backend) { - return backend.keys(); - } - ); + [&](detail::abstract_backend& backend) { return backend.keys(); }); } expected exists(const data& key) const override { return perform( - [&](detail::abstract_backend& backend) { - return backend.exists(key); - } - ); + [&](detail::abstract_backend& backend) { return backend.exists(key); }); } expected size() const override { return perform( - [](detail::abstract_backend& backend) { - return backend.size(); - } - ); + [](detail::abstract_backend& backend) { return backend.size(); }); } expected snapshot() const override { return perform( - [](detail::abstract_backend& backend) { - return backend.snapshot(); - } - ); + [](detail::abstract_backend& backend) { return backend.snapshot(); }); } expected expiries() const override { return perform( - [](detail::abstract_backend& backend) { - return backend.expiries(); - } - ); + [](detail::abstract_backend& backend) { return backend.expiries(); }); } private: @@ -203,13 +169,13 @@ struct fixture : base_fixture { } }; -} // namespace +} // namespace FIXTURE_SCOPE(backend_tests, fixture) #define RUN(statement) run([&] { return statement; }, #statement) -TEST(put/get) { +TEST(put / get) { RUN(backend->put("foo", 7)); CHECK_EQUAL(RUN(backend->get("foo")), data{7}); MESSAGE("overwrite"); @@ -222,7 +188,7 @@ TEST(put/get) { CHECK_EQUAL(bar.error(), ec::no_such_key); } -TEST(add/remove) { +TEST(add / remove) { backend->put("foo", 0); auto add = backend->add("foo", 42, data::type::integer); REQUIRE(add); @@ -255,7 +221,7 @@ TEST(add/remove) { CHECK_EQUAL(*get, data{34}); } -TEST(erase/exists) { +TEST(erase / exists) { using namespace std::chrono; auto exists = backend->exists("foo"); REQUIRE(exists); @@ -278,7 +244,7 @@ TEST(erase/exists) { REQUIRE(erase); } -TEST(clear/keys) { +TEST(clear / keys) { using namespace std::chrono; auto put = backend->put("foo", "1"); REQUIRE(put); @@ -325,7 +291,7 @@ TEST(expiration without expiry) { REQUIRE(!*expire); // no expiry with key associated } -TEST(size/snapshot) { +TEST(size / snapshot) { using namespace std::chrono; auto put = backend->put("foo", "bar"); REQUIRE(put); diff --git a/tests/cpp/core.cc b/tests/cpp/core.cc index d4f33f02..da44324e 100644 --- a/tests/cpp/core.cc +++ b/tests/cpp/core.cc @@ -28,8 +28,16 @@ struct driver_state { buf_type xs; static inline const char* name = "driver"; void reset() { - xs = data_msgs({{"a", 0}, {"b", true}, {"a", 1}, {"a", 2}, {"b", false}, - {"b", true}, {"a", 3}, {"b", false}, {"a", 4}, {"a", 5}}); + xs = data_msgs({{"a", 0}, + {"b", true}, + {"a", 1}, + {"a", 2}, + {"b", false}, + {"b", true}, + {"a", 3}, + {"b", false}, + {"a", 4}, + {"a", 5}}); } driver_state() { reset(); @@ -39,37 +47,37 @@ struct driver_state { caf::behavior driver(caf::stateful_actor* self, const caf::actor& sink, bool restartable) { self->state.restartable = restartable; - auto ptr - = attach_stream_source( - self, - // Destination. - sink, - // Initialize send buffer with 10 elements. - [](caf::unit_t&) { - // nop - }, - // Get next element. - [=](caf::unit_t&, caf::downstream& out, size_t num) { - auto& xs = self->state.xs; - auto n = std::min(num, xs.size()); - if (n == 0) - return; - for (size_t i = 0u; i < n; ++i) - out.push(xs[i]); - xs.erase(xs.begin(), xs.begin() + static_cast(n)); - }, - // Did we reach the end?. - [=](const caf::unit_t&) { - auto& st = self->state; - return !st.restartable && st.xs.empty(); - }) - .ptr(); + auto ptr = + attach_stream_source( + self, + // Destination. + sink, + // Initialize send buffer with 10 elements. + [](caf::unit_t&) { + // nop + }, + // Get next element. + [=](caf::unit_t&, caf::downstream& out, size_t num) { + auto& xs = self->state.xs; + auto n = std::min(num, xs.size()); + if (n == 0) + return; + for (size_t i = 0u; i < n; ++i) + out.push(xs[i]); + xs.erase(xs.begin(), xs.begin() + static_cast(n)); + }, + // Did we reach the end?. + [=](const caf::unit_t&) { + auto& st = self->state; + return !st.restartable && st.xs.empty(); + }) + .ptr(); return { [=](atom::restart) { self->state.reset(); self->state.restartable = false; ptr->push(); - } + }, }; } @@ -106,7 +114,7 @@ caf::behavior consumer(caf::stateful_actor* self, }; } -} // namespace +} // namespace // Simulates a simple setup with two cores, where data flows from core1 to // core2. @@ -171,13 +179,11 @@ CAF_TEST(local_peers) { self->send(leaf, atom::get_v); sched.prioritize(leaf); consume_message(); - self->receive( - [](const buf& xs) { - auto expected = data_msgs({{"b", true}, {"b", false}, - {"b", true}, {"b", false}}); - CAF_REQUIRE_EQUAL(xs, expected); - } - ); + self->receive([](const buf& xs) { + auto expected = + data_msgs({{"b", true}, {"b", false}, {"b", true}, {"b", false}}); + CAF_REQUIRE_EQUAL(xs, expected); + }); CAF_MESSAGE("send message 'directly' from core1 to core2 (bypass streaming)"); anon_send(core1, atom::publish_v, endpoint_info{facade(core2.node()), std::nullopt}, @@ -192,13 +198,11 @@ CAF_TEST(local_peers) { self->send(leaf, atom::get_v); sched.prioritize(leaf); consume_message(); - self->receive( - [](const buf& xs) { - auto expected = data_msgs({{"b", true}, {"b", false}, {"b", true}, - {"b", false}, {"b", true}}); - CAF_REQUIRE_EQUAL(xs, expected); - } - ); + self->receive([](const buf& xs) { + auto expected = data_msgs( + {{"b", true}, {"b", false}, {"b", true}, {"b", false}, {"b", true}}); + CAF_REQUIRE_EQUAL(xs, expected); + }); CAF_MESSAGE("unpeer core1 from core2"); anon_send(core1, atom::unpeer_v, core2); run(); @@ -313,17 +317,13 @@ CAF_TEST(triangle_peering) { run(); // Check log of the consumers. using buf = std::vector; - auto expected = data_msgs({{"b", true}, {"b", false}, - {"b", true}, {"b", false}}); + auto expected = + data_msgs({{"b", true}, {"b", false}, {"b", true}, {"b", false}}); for (auto& leaf : {leaf2, leaf3}) { self->send(leaf, atom::get_v); sched.prioritize(leaf); consume_message(); - self->receive( - [&](const buf& xs) { - CAF_REQUIRE_EQUAL(xs, expected); - } - ); + self->receive([&](const buf& xs) { CAF_REQUIRE_EQUAL(xs, expected); }); } // Make sure leaf1 never received any data. self->send(leaf1, atom::get_v); @@ -385,16 +385,12 @@ CAF_TEST(sequenced_peering) { run(); // Check log of the consumer on core2. using buf = std::vector; - auto expected = data_msgs({{"b", true}, {"b", false}, - {"b", true}, {"b", false}}); + auto expected = + data_msgs({{"b", true}, {"b", false}, {"b", true}, {"b", false}}); self->send(leaf1, atom::get_v); sched.prioritize(leaf1); consume_message(); - self->receive( - [&](const buf& xs) { - CAF_REQUIRE_EQUAL(xs, expected); - } - ); + self->receive([&](const buf& xs) { CAF_REQUIRE_EQUAL(xs, expected); }); CAF_MESSAGE("kill core2"); anon_send_exit(core2, caf::exit_reason::user_shutdown); run(); @@ -451,8 +447,8 @@ struct error_signaling_fixture : base_fixture { core1 = native(ep.core()); CAF_MESSAGE(BROKER_ARG(core1)); anon_send(core1, atom::subscribe_v, filter_type{"a", "b", "c"}); - core2 - = sys.spawn(filter_type{"a", "b", "c"}, ep.options()); + core2 = sys.spawn(filter_type{"a", "b", "c"}, + ep.options()); CAF_MESSAGE(BROKER_ARG(core2)); run(); CAF_MESSAGE("init done"); @@ -494,7 +490,7 @@ struct event_visitor { } \ CAF_VOID_STMT -} // namespace +} // namespace CAF_TEST_FIXTURE_SCOPE(error_signaling, error_signaling_fixture) @@ -643,13 +639,11 @@ CAF_TEST(remote_peers_setup1) { using buf = std::vector; earth.self->send(leaf, atom::get_v); exec_all(); - earth.self->receive( - [](const buf& xs) { - auto expected = data_msgs({{"b", true}, {"b", false}, - {"b", true}, {"b", false}}); - CAF_REQUIRE_EQUAL(xs, expected); - } - ); + earth.self->receive([](const buf& xs) { + auto expected = + data_msgs({{"b", true}, {"b", false}, {"b", true}, {"b", false}}); + CAF_REQUIRE_EQUAL(xs, expected); + }); anon_send_exit(core1, caf::exit_reason::user_shutdown); anon_send_exit(core2, caf::exit_reason::user_shutdown); anon_send_exit(leaf, caf::exit_reason::user_shutdown); @@ -704,13 +698,11 @@ CAF_TEST(remote_peers_setup2) { mars.self->send(leaf, atom::get_v); mars.sched.prioritize(leaf); mars.consume_message(); - mars.self->receive( - [](const buf& xs) { - auto expected = data_msgs({{"b", true}, {"b", false}, - {"b", true}, {"b", false}}); - CAF_REQUIRE_EQUAL(xs, expected); - } - ); + mars.self->receive([](const buf& xs) { + auto expected = + data_msgs({{"b", true}, {"b", false}, {"b", true}, {"b", false}}); + CAF_REQUIRE_EQUAL(xs, expected); + }); CAF_MESSAGE("shutdown core actors"); anon_send_exit(core1, caf::exit_reason::user_shutdown); anon_send_exit(core2, caf::exit_reason::user_shutdown); diff --git a/tests/cpp/error.cc b/tests/cpp/error.cc index 0e112295..db499c66 100644 --- a/tests/cpp/error.cc +++ b/tests/cpp/error.cc @@ -86,19 +86,19 @@ TEST(errors with category broker are convertible to and from data) { ec::peer_invalid, endpoint_info{ids['B'], network_info{"foo", 8080, timeout::seconds{42}}}, "invalid host"s)), - make_data_error( - ec::peer_invalid, - {vector{str_ids['B'], "foo"s, port{8080, port::protocol::tcp}, count{42}}, - "invalid host"s})); + make_data_error(ec::peer_invalid, + {vector{str_ids['B'], "foo"s, + port{8080, port::protocol::tcp}, count{42}}, + "invalid host"s})); CHECK_EQUAL( get_as(make_data_error( ec::peer_invalid, {vector{str_ids['B'], "foo"s, port{8080, port::protocol::tcp}, count{42}}, "invalid host"s})), - make_error( - ec::peer_invalid, - endpoint_info{ids['B'], network_info{"foo", 8080, timeout::seconds{42}}}, - "invalid host"s)); + make_error(ec::peer_invalid, + endpoint_info{ids['B'], + network_info{"foo", 8080, timeout::seconds{42}}}, + "invalid host"s)); CHECK_EQUAL( get_as(make_data_error( ec::peer_invalid, diff --git a/tests/cpp/filter_type.cc b/tests/cpp/filter_type.cc index 6e1e5020..c3833be2 100644 --- a/tests/cpp/filter_type.cc +++ b/tests/cpp/filter_type.cc @@ -24,7 +24,7 @@ FIXTURE_SCOPE(filter_tests, fixture) TEST(extending a filter with less specific topics truncates) { auto f = make("/foo/bar", "/foo/baz", "/zeek"); filter_extend(f, "/foo"); - CHECK_EQUAL(f, make("/foo","/zeek")); + CHECK_EQUAL(f, make("/foo", "/zeek")); } TEST(extending a filter with unrelated topics appends) { diff --git a/tests/cpp/integration.cc b/tests/cpp/integration.cc index 43f5d984..c6e8c7ff 100644 --- a/tests/cpp/integration.cc +++ b/tests/cpp/integration.cc @@ -137,13 +137,10 @@ struct peer_fixture { [](unit_t&) { // nop }, - [=](unit_t&, data_message x) { - this->data.emplace_back(std::move(x)); - }, + [=](unit_t&, data_message x) { this->data.emplace_back(std::move(x)); }, [](unit_t&, const error&) { // nop - } - ); + }); parent->exec_loop(); } @@ -167,7 +164,7 @@ struct peer_fixture { } void loop_after_next_enqueue() { - sched.after_next_enqueue([=] { parent->exec_loop(); }); + sched.after_next_enqueue([=] { parent->exec_loop(); }); } void loop_after_all_enqueues_helper() { @@ -176,7 +173,7 @@ struct peer_fixture { } void loop_after_all_enqueues() { - sched.after_next_enqueue([=] { loop_after_all_enqueues_helper(); }); + sched.after_next_enqueue([=] { loop_after_all_enqueues_helper(); }); } }; @@ -216,10 +213,7 @@ struct triangle_fixture : global_fixture { peer_fixture earth; triangle_fixture() - : mercury(this, "mercury"), - venus(this, "venus"), - earth(this, "earth") { - } + : mercury(this, "mercury"), venus(this, "venus"), earth(this, "earth") {} // Connect mercury to venus and earth. void connect_peers() { @@ -234,8 +228,8 @@ struct triangle_fixture : global_fixture { "mercury", 4040, earth.make_connection_handle()); MESSAGE("start listening on mercury:4040"); - // We need to connect venus and earth while mercury is blocked on ep.listen() - // in order to avoid a "deadlock" in `ep.listen()`. + // We need to connect venus and earth while mercury is blocked on + // ep.listen() in order to avoid a "deadlock" in `ep.listen()`. mercury.sched.after_next_enqueue([&] { exec_loop(); MESSAGE("peer venus to mercury:4040"); @@ -245,12 +239,12 @@ struct triangle_fixture : global_fixture { earth.loop_after_next_enqueue(); earth.ep.peer("mercury", 4040); }); - //mercury.sched.inline_next_enqueue(); + // mercury.sched.inline_next_enqueue(); mercury.ep.listen("", 4040); } }; -} // namespace +} // namespace CAF_TEST_FIXTURE_SCOPE(triangle_use_cases, triangle_fixture) @@ -288,8 +282,7 @@ CAF_TEST(topic_prefix_matching_async_subscribe) { CAF_CHECK_EQUAL(venus.ep.peer_subscriptions(), filter_type({"zeek/events/errors"})); earth.loop_after_next_enqueue(); - CAF_CHECK_EQUAL(earth.ep.peer_subscriptions(), - filter_type({"zeek/events"})); + CAF_CHECK_EQUAL(earth.ep.peer_subscriptions(), filter_type({"zeek/events"})); MESSAGE("publish to 'zeek/events/(data|errors)' on mercury"); mercury.publish("zeek/events/errors", "oops", "sorry!"); mercury.publish("zeek/events/data", 123, 456); @@ -348,16 +341,14 @@ CAF_TEST(topic_prefix_matching_make_subscriber) { mercury.publish("zeek/events/errors", "oops", "sorry!"); mercury.publish("zeek/events/data", 123, 456); MESSAGE("verify published data"); - CAF_CHECK_EQUAL(venus_s1.poll(), - data_msgs({{"zeek/events/errors", "oops"}, - {"zeek/events/errors", "sorry!"}, - {"zeek/events/data", 123}, - {"zeek/events/data", 456}})); - CAF_CHECK_EQUAL(venus_s2.poll(), - data_msgs({{"zeek/events/errors", "oops"}, - {"zeek/events/errors", "sorry!"}, - {"zeek/events/data", 123}, - {"zeek/events/data", 456}})); + CAF_CHECK_EQUAL(venus_s1.poll(), data_msgs({{"zeek/events/errors", "oops"}, + {"zeek/events/errors", "sorry!"}, + {"zeek/events/data", 123}, + {"zeek/events/data", 456}})); + CAF_CHECK_EQUAL(venus_s2.poll(), data_msgs({{"zeek/events/errors", "oops"}, + {"zeek/events/errors", "sorry!"}, + {"zeek/events/data", 123}, + {"zeek/events/data", 456}})); CAF_CHECK_EQUAL(earth_s1.poll(), data_msgs({{"zeek/events/errors", "oops"}, {"zeek/events/errors", "sorry!"}})); @@ -491,23 +482,21 @@ CAF_TEST(connection_retry) { MESSAGE("spawn helper that starts listening on mercury:4040 eventually"); mercury.sys.spawn([&](caf::event_based_actor* self) -> caf::behavior { self->delayed_send(self, std::chrono::seconds(2), atom::ok_v); - return { - [&](caf::ok_atom) { - MESSAGE("start listening on mercury:4040"); - auto server_handle = mercury.make_accept_handle(); - mercury.mpx.prepare_connection(server_handle, - mercury.make_connection_handle(), - venus.mpx, "mercury", 4040, - venus.make_connection_handle()); - // We need to connect venus while mercury is blocked on ep.listen() in - // order to avoid a "deadlock" in `ep.listen()`. - mercury.sched.after_next_enqueue([&] { - MESSAGE("peer venus to mercury:4040 by triggering the retry timeout"); - exec_loop(); - }); - mercury.ep.listen("", 4040); - } - }; + return {[&](caf::ok_atom) { + MESSAGE("start listening on mercury:4040"); + auto server_handle = mercury.make_accept_handle(); + mercury.mpx.prepare_connection(server_handle, + mercury.make_connection_handle(), + venus.mpx, "mercury", 4040, + venus.make_connection_handle()); + // We need to connect venus while mercury is blocked on ep.listen() in + // order to avoid a "deadlock" in `ep.listen()`. + mercury.sched.after_next_enqueue([&] { + MESSAGE("peer venus to mercury:4040 by triggering the retry timeout"); + exec_loop(); + }); + mercury.ep.listen("", 4040); + }}; }); exec_loop(); MESSAGE("check event logs"); @@ -522,4 +511,3 @@ CAF_TEST(connection_retry) { } CAF_TEST_FIXTURE_SCOPE_END() - diff --git a/tests/cpp/internal/channel.cc b/tests/cpp/internal/channel.cc index f2197905..4638721c 100644 --- a/tests/cpp/internal/channel.cc +++ b/tests/cpp/internal/channel.cc @@ -39,7 +39,7 @@ struct consumer_backend { // nop } - void attach(caf::event_based_actor* self, fixture*fix) { + void attach(caf::event_based_actor* self, fixture* fix) { this->self = self; this->fix = fix; } @@ -81,7 +81,6 @@ caf::behavior producer_actor(caf::event_based_actor* self, producer_type* state); struct fixture : base_fixture { - struct outgoing_message { caf::actor sender; caf::actor receiver; diff --git a/tests/cpp/internal/core_actor.cc b/tests/cpp/internal/core_actor.cc index be5c5748..7f34975b 100644 --- a/tests/cpp/internal/core_actor.cc +++ b/tests/cpp/internal/core_actor.cc @@ -17,7 +17,7 @@ namespace { struct config : public caf::actor_system_config { config() { set("caf.logger.file.verbosity", "trace"); - //set("caf.logger.console.verbosity", "trace"); + // set("caf.logger.console.verbosity", "trace"); } }; @@ -112,7 +112,7 @@ auto ids(Ts... xs) { return std::vector{xs...}; } -} // namespace +} // namespace FIXTURE_SCOPE(local_tests, fixture) diff --git a/tests/cpp/internal/json_type_mapper.cc b/tests/cpp/internal/json_type_mapper.cc index 91ffbe04..10adb783 100644 --- a/tests/cpp/internal/json_type_mapper.cc +++ b/tests/cpp/internal/json_type_mapper.cc @@ -146,7 +146,7 @@ data_message native() { data{std::move(xs)}}; } -} // namespace +} // namespace TEST(the JSON mapper enables custom type names in JSON input) { internal::json_type_mapper mapper; diff --git a/tests/cpp/internal/meta_command_writer.cc b/tests/cpp/internal/meta_command_writer.cc index d2428a04..97c87b55 100644 --- a/tests/cpp/internal/meta_command_writer.cc +++ b/tests/cpp/internal/meta_command_writer.cc @@ -90,7 +90,8 @@ CAF_TEST(erase_command) { } CAF_TEST(add_command) { - push(add_command{data{"key"}, data{"value"}, data::type::table, std::nullopt}); + push( + add_command{data{"key"}, data{"value"}, data::type::table, std::nullopt}); CHECK_EQUAL(pull(), internal_command::type::add_command); CHECK_EQUAL(pull(), data::type::string); diff --git a/tests/cpp/internal/meta_data_writer.cc b/tests/cpp/internal/meta_data_writer.cc index 3e4fbcc3..007a8df8 100644 --- a/tests/cpp/internal/meta_data_writer.cc +++ b/tests/cpp/internal/meta_data_writer.cc @@ -186,8 +186,8 @@ CAF_TEST(vector data) { } CAF_TEST(put_command) { - auto cmd = internal_command{0, {}, put_command{data{"hello"}, - data{"broker"}, std::nullopt}}; + auto cmd = internal_command{ + 0, {}, put_command{data{"hello"}, data{"broker"}, std::nullopt}}; push(cmd); CHECK_EQUAL(buf.size(), 11u); CHECK_EQUAL(pull(), @@ -200,11 +200,11 @@ CAF_TEST(put_command) { } CAF_TEST(put_unique_command) { - auto cmd - = internal_command{0, - {}, - put_unique_command{data{"hello"}, data{"broker"}, - std::nullopt, entity_id::nil(), 0}}; + auto cmd = + internal_command{0, + {}, + put_unique_command{data{"hello"}, data{"broker"}, + std::nullopt, entity_id::nil(), 0}}; push(cmd); CHECK_EQUAL(pull(), internal_command::type::put_unique_command); @@ -227,10 +227,11 @@ CAF_TEST(erase_command) { } CAF_TEST(add_command) { - auto cmd = internal_command{0, {}, - add_command{data{"key"}, data{"value"}, - data::type::table, std::nullopt, - entity_id::nil()}}; + auto cmd = + internal_command{0, + {}, + add_command{data{"key"}, data{"value"}, data::type::table, + std::nullopt, entity_id::nil()}}; push(cmd); CHECK_EQUAL(pull(), internal_command::type::add_command); @@ -242,8 +243,8 @@ CAF_TEST(add_command) { } CAF_TEST(subtract_command) { - auto cmd = internal_command{0, {}, subtract_command{data{"key"}, - data{"value"}, std::nullopt}}; + auto cmd = internal_command{ + 0, {}, subtract_command{data{"key"}, data{"value"}, std::nullopt}}; push(cmd); CHECK_EQUAL(pull(), internal_command::type::subtract_command); diff --git a/tests/cpp/internal/metric_collector.cc b/tests/cpp/internal/metric_collector.cc index b0575c8c..222373d1 100644 --- a/tests/cpp/internal/metric_collector.cc +++ b/tests/cpp/internal/metric_collector.cc @@ -54,8 +54,9 @@ struct fixture : base_fixture { "Int Histogram!", "seconds"); foo_h1 = h1_fam->get_or_add({{"sys", "broker"}}); std::array dbl_buckets{{8.0, 16.0, 32.0}}; - auto h2_fam = reg.histogram_family( - "foo", "h2", {"sys"}, dbl_buckets, "Dbl Histogram!", "seconds"); + auto h2_fam = reg.histogram_family("foo", "h2", {"sys"}, + dbl_buckets, "Dbl Histogram!", + "seconds"); foo_h2 = h2_fam->get_or_add({{"sys", "broker"}}); // Spin up actors. core = sys.spawn(dummy_core, collector_ptr{&collector}); diff --git a/tests/cpp/internal/metric_exporter.cc b/tests/cpp/internal/metric_exporter.cc index 3cbaa4d7..660d1a85 100644 --- a/tests/cpp/internal/metric_exporter.cc +++ b/tests/cpp/internal/metric_exporter.cc @@ -89,9 +89,10 @@ struct fixture : base_fixture { bar_foo = reg.gauge_singleton("bar", "foo", "BarFoo!"); std::vector selection{"foo"}; core = sys.spawn(); - aut = sys.spawn( - core, std::move(selection), caf::timespan{2s}, "all/them/metrics", - "exporter-1"); + aut = sys.spawn(core, std::move(selection), + caf::timespan{2s}, + "all/them/metrics", + "exporter-1"); sched.run(); } diff --git a/tests/cpp/publisher.cc b/tests/cpp/publisher.cc index 65b6eb80..8fb8ceaa 100644 --- a/tests/cpp/publisher.cc +++ b/tests/cpp/publisher.cc @@ -44,7 +44,7 @@ namespace { struct no_state {}; -} // namespace +} // namespace FIXTURE_SCOPE(publisher_tests, net_fixture) diff --git a/tests/cpp/radix_tree.cc b/tests/cpp/radix_tree.cc index d02c66ff..87f83be1 100644 --- a/tests/cpp/radix_tree.cc +++ b/tests/cpp/radix_tree.cc @@ -84,7 +84,7 @@ unsigned char key2[303] = { 219, 191, 198, 134, 5, 208, 212, 72, 44, 208, 250, 180, 14, 1, 0, 0, 8, '\0'}; -} // namespace +} // namespace TEST(very long insert) { detail::radix_tree rt; @@ -144,7 +144,7 @@ TEST(prefix_of) { {make_pair("one", 1), make_pair("one-hundred", 100)})); CHECK(check_match(t.prefix_of("one-hundred-thousand"), {make_pair("one", 1), make_pair("one-hundred", 100), - make_pair("one-hundred-thousand", 100000)})); + make_pair("one-hundred-thousand", 100000)})); CHECK(check_match(t.prefix_of("one-hundred-two"), {make_pair("one", 1), make_pair("one-hundred", 100)})); t["two"] = 2; @@ -156,7 +156,7 @@ TEST(prefix_of) { {make_pair("one", 1), make_pair("one-hundred", 100)})); CHECK(check_match(t.prefix_of("one-hundred-thousand"), {make_pair("one", 1), make_pair("one-hundred", 100), - make_pair("one-hundred-thousand", 100000)})); + make_pair("one-hundred-thousand", 100000)})); CHECK(check_match(t.prefix_of("one-hundred-two"), {make_pair("one", 1), make_pair("one-hundred", 100)})); t["two-fifty"] = 250; @@ -168,7 +168,7 @@ TEST(prefix_of) { {make_pair("one", 1), make_pair("one-hundred", 100)})); CHECK(check_match(t.prefix_of("one-hundred-thousand"), {make_pair("one", 1), make_pair("one-hundred", 100), - make_pair("one-hundred-thousand", 100000)})); + make_pair("one-hundred-thousand", 100000)})); CHECK(check_match(t.prefix_of("one-hundred-two"), {make_pair("one", 1), make_pair("one-hundred", 100)})); CHECK(check_match(t.prefix_of("two-fifty-five"), @@ -183,7 +183,7 @@ TEST(prefix_of) { {make_pair("one", 1), make_pair("one-hundred", 100)})); CHECK(check_match(t.prefix_of("one-hundred-thousand"), {make_pair("one", 1), make_pair("one-hundred", 100), - make_pair("one-hundred-thousand", 100000)})); + make_pair("one-hundred-thousand", 100000)})); CHECK(check_match(t.prefix_of("one-hundred-two"), {make_pair("one", 1), make_pair("one-hundred", 100)})); CHECK(check_match(t.prefix_of("two-fifty-five"), @@ -192,8 +192,8 @@ TEST(prefix_of) { CHECK(check_match(t.prefix_of(""), {make_pair("", -1)})); CHECK(check_match(t.prefix_of("nope"), {make_pair("", -1)})); CHECK(check_match(t.prefix_of("on"), {make_pair("", -1)})); - CHECK(check_match(t.prefix_of("one"), - {make_pair("", -1), make_pair("one", 1)})); + CHECK( + check_match(t.prefix_of("one"), {make_pair("", -1), make_pair("one", 1)})); CHECK(check_match(t.prefix_of("one-hundred"), {make_pair("", -1), make_pair("one", 1), make_pair("one-hundred", 100)})); @@ -216,29 +216,34 @@ TEST(prefix match) { }; CHECK(check_match(t.prefixed_by("api"), {make_pair("api", 6), make_pair("api.foe.fum", 3), - make_pair("api.foo", 5), make_pair("api.foo.bar", 1), - make_pair("api.foo.baz", 2)})); - CHECK(check_match(t.prefixed_by("a"), - {make_pair("abc.123.456", 4), make_pair("api", 6), - make_pair("api.foe.fum", 3), make_pair("api.foo", 5), - make_pair("api.foo.bar", 1), make_pair("api.foo.baz", 2) - })); + make_pair("api.foo", 5), make_pair("api.foo.bar", 1), + make_pair("api.foo.baz", 2)})); + CHECK( + check_match(t.prefixed_by("a"), + {make_pair("abc.123.456", 4), make_pair("api", 6), + make_pair("api.foe.fum", 3), make_pair("api.foo", 5), + make_pair("api.foo.bar", 1), make_pair("api.foo.baz", 2)})); CHECK(t.prefixed_by("b").empty()); - CHECK(check_match(t.prefixed_by("api."), - {make_pair("api.foe.fum", 3), make_pair("api.foo", 5), - make_pair("api.foo.bar", 1), make_pair("api.foo.baz", 2), - })); - CHECK(check_match(t.prefixed_by("api.foo.bar"), - {make_pair("api.foo.bar", 1)})); + CHECK(check_match(t.prefixed_by("api."), { + make_pair("api.foe.fum", 3), + make_pair("api.foo", 5), + make_pair("api.foo.bar", 1), + make_pair("api.foo.baz", 2), + })); + CHECK( + check_match(t.prefixed_by("api.foo.bar"), {make_pair("api.foo.bar", 1)})); CHECK(t.prefixed_by("api.end").empty()); - CHECK(check_match(t.prefixed_by(""), - {make_pair("abc.123.456", 4), make_pair("api", 6), - make_pair("api.foe.fum", 3), make_pair("api.foo", 5), - make_pair("api.foo.bar", 1), make_pair("api.foo.baz", 2), - })); + CHECK(check_match(t.prefixed_by(""), { + make_pair("abc.123.456", 4), + make_pair("api", 6), + make_pair("api.foe.fum", 3), + make_pair("api.foo", 5), + make_pair("api.foo.bar", 1), + make_pair("api.foo.baz", 2), + })); CHECK(check_match(t.prefix_of("api.foo.bar.baz"), {make_pair("api", 6), make_pair("api.foo", 5), - make_pair("api.foo.bar", 1)})); + make_pair("api.foo.bar", 1)})); CHECK(check_match(t.prefix_of("api.foo.fum"), {make_pair("api", 6), make_pair("api.foo", 5)})); CHECK(t.prefix_of("").empty()); @@ -263,15 +268,11 @@ TEST(many keys) { for (const auto& p : matches) CHECK(p->first[0] == '1'); matches = t.prefix_of("109876"); - CHECK(check_match(matches, - {make_pair("109", 109), - make_pair("10", 10), - make_pair("1", 1)})); + CHECK(check_match(matches, {make_pair("109", 109), make_pair("10", 10), + make_pair("1", 1)})); matches = t.prefix_of("54321"); - CHECK(check_match(matches, - {make_pair("543", 543), - make_pair("54", 54), - make_pair("5", 5)})); + CHECK(check_match(matches, {make_pair("543", 543), make_pair("54", 54), + make_pair("5", 5)})); for (int i = 0; i < 500; ++i) { CHECK(t.erase(keys[i]) == 1); CHECK(t.erase(keys[i]) == 0); @@ -305,10 +306,8 @@ TEST(many keys) { for (const auto& p : matches) CHECK(p->first[0] == '9'); matches = t.prefix_of("54321"); - CHECK(check_match(matches, - {make_pair("543", 543), - make_pair("54", 54), - make_pair("5", 5)})); + CHECK(check_match(matches, {make_pair("543", 543), make_pair("54", 54), + make_pair("5", 5)})); t.clear(); CHECK(t.size() == 0); } @@ -403,10 +402,9 @@ TEST(general) { matches = tree.prefixed_by("bi"); CHECK(check_match(matches, {make_pair("binary", 5), make_pair("bind", 6)})); matches = tree.prefixed_by("a"); - CHECK(check_match(matches, - {make_pair("apache", 0), make_pair("afford", 1), - make_pair("available", 2), make_pair("affair", 3), - make_pair("avenger", 4)})); + CHECK(check_match(matches, {make_pair("apache", 0), make_pair("afford", 1), + make_pair("available", 2), make_pair("affair", 3), + make_pair("avenger", 4)})); matches = tree.prefixed_by(""); CHECK(tree.size() == 10); CHECK(matches.size() == tree.size()); @@ -430,28 +428,25 @@ TEST(general) { CHECK(tree.insert(make_pair("bro", 42)).second == true); CHECK(tree.size() == 12); matches = tree.prefixed_by("b"); - CHECK(check_match(matches, - {make_pair("bind", 6), make_pair("binary", 5), - make_pair("blind", 9), make_pair("brace", 8), - make_pair("bro", 42), make_pair("brother", 7)})); + CHECK(check_match(matches, {make_pair("bind", 6), make_pair("binary", 5), + make_pair("blind", 9), make_pair("brace", 8), + make_pair("bro", 42), make_pair("brother", 7)})); CHECK(tree.erase("nope") == 0); CHECK(tree.erase("a") == 0); CHECK(tree.size() == 12); CHECK(tree.erase("bro") == 1); CHECK(tree.size() == 11); matches = tree.prefixed_by("b"); - CHECK(check_match(matches, - {make_pair("bind", 6), make_pair("binary", 5), - make_pair("blind", 9), make_pair("brace", 8), - make_pair("brother", 7)})); + CHECK(check_match(matches, {make_pair("bind", 6), make_pair("binary", 5), + make_pair("blind", 9), make_pair("brace", 8), + make_pair("brother", 7)})); CHECK(tree.insert(make_pair("bro", 42)).second == true); CHECK(tree.size() == 12); CHECK(tree.erase("brother") == 1); matches = tree.prefixed_by("b"); - CHECK(check_match(matches, - {make_pair("bind", 6), make_pair("binary", 5), - make_pair("blind", 9), make_pair("brace", 8), - make_pair("bro", 42)})); + CHECK(check_match(matches, {make_pair("bind", 6), make_pair("binary", 5), + make_pair("blind", 9), make_pair("brace", 8), + make_pair("bro", 42)})); CHECK(tree.erase("brace") == 1); CHECK(tree.erase("bind") == 1); CHECK(tree.erase("blind") == 1); @@ -463,15 +458,12 @@ TEST(general) { CHECK(tree.insert(make_pair("brother", 2)).second == true); CHECK(tree.size() == 3); matches = tree.prefixed_by("bro"); - CHECK(check_match(matches, - {make_pair("bro", 42), make_pair("bros", 1), - make_pair("brother", 2)})); + CHECK(check_match(matches, {make_pair("bro", 42), make_pair("bros", 1), + make_pair("brother", 2)})); matches = tree.prefix_of("bros"); - CHECK(check_match(matches, - {make_pair("bro", 42), make_pair("bros", 1)})); + CHECK(check_match(matches, {make_pair("bro", 42), make_pair("bros", 1)})); matches = tree.prefix_of("brothers"); - CHECK(check_match(matches, - {make_pair("bro", 42), make_pair("brother", 2)})); + CHECK(check_match(matches, {make_pair("bro", 42), make_pair("brother", 2)})); CHECK(tree.erase("brother") == 1); CHECK(tree.erase("bros") == 1); CHECK(tree.size() == 1); diff --git a/tests/cpp/ssl.cc b/tests/cpp/ssl.cc index 050b3d15..c31fda91 100644 --- a/tests/cpp/ssl.cc +++ b/tests/cpp/ssl.cc @@ -50,8 +50,7 @@ struct peer_fixture { // Initializes this peer and registers it at parent. peer_fixture(std::string peer_name, configuration config) - : name(std::move(peer_name)), - ep(std::move(config)){} + : name(std::move(peer_name)), ep(std::move(config)) {} }; // A fixture for testing SSL authentication. @@ -65,11 +64,10 @@ struct ssl_auth_fixture { : mercury_auth("mercury_auth", make_config("1")), venus_auth("venus_auth", make_config("2")), earth_no_auth("earth_no_auth", make_config("")), - earth_wrong_auth("earth_wrong_auth", make_config("self-signed")) { - } + earth_wrong_auth("earth_wrong_auth", make_config("self-signed")) {} }; -} // namespace +} // namespace FIXTURE_SCOPE(ssl_auth_use_cases, ssl_auth_fixture) diff --git a/tests/cpp/status.cc b/tests/cpp/status.cc index 0c4f40f3..f76ceb69 100644 --- a/tests/cpp/status.cc +++ b/tests/cpp/status.cc @@ -51,7 +51,8 @@ TEST(sc is convertible to and from string) { CHECK_EQUAL(from_string("peer_removed"), sc::peer_removed); CHECK_EQUAL(from_string("peer_lost"), sc::peer_lost); CHECK_EQUAL(from_string("endpoint_discovered"), sc::endpoint_discovered); - CHECK_EQUAL(from_string("endpoint_unreachable"), sc::endpoint_unreachable); + CHECK_EQUAL(from_string("endpoint_unreachable"), + sc::endpoint_unreachable); CHECK_EQUAL(from_string("foo"), std::nullopt); } diff --git a/tests/cpp/status_subscriber.cc b/tests/cpp/status_subscriber.cc index 5e494d1c..fbe87a52 100644 --- a/tests/cpp/status_subscriber.cc +++ b/tests/cpp/status_subscriber.cc @@ -51,7 +51,7 @@ struct fixture : base_fixture { } }; -} // namespace +} // namespace FIXTURE_SCOPE(status_subscriber_tests, fixture) diff --git a/tests/cpp/store_event.cc b/tests/cpp/store_event.cc index b4141688..1a2c7ce1 100644 --- a/tests/cpp/store_event.cc +++ b/tests/cpp/store_event.cc @@ -107,7 +107,8 @@ TEST(update events consist of key value and expiry) { } MESSAGE("elements six and seven denote the publisher"); { - data x{vector{"update"s, "x"s, "foo"s, "bar"s, "baz"s, nil, str_ids['B'], obj}}; + data x{ + vector{"update"s, "x"s, "foo"s, "bar"s, "baz"s, nil, str_ids['B'], obj}}; auto view = store_event::update::make(x); REQUIRE(view); CHECK_EQUAL(view.store_id(), "x"s); diff --git a/tests/cpp/subscriber.cc b/tests/cpp/subscriber.cc index ee526c01..525c8365 100644 --- a/tests/cpp/subscriber.cc +++ b/tests/cpp/subscriber.cc @@ -50,7 +50,7 @@ struct fixture : net_fixture { } }; -} // namespace +} // namespace FIXTURE_SCOPE(subscriber_tests, fixture) diff --git a/tests/cpp/system/peering.cc b/tests/cpp/system/peering.cc index fc3d4b3b..c673ee89 100644 --- a/tests/cpp/system/peering.cc +++ b/tests/cpp/system/peering.cc @@ -70,9 +70,9 @@ configuration make_config(const char* test_name, size_t endpoint_nr, cfg.set("caf.logger.file.path", log_path_template(test_name, endpoint_nr)); // cfg.set("caf.logger.file.verbosity", "trace"); // cfg.set("caf.logger.file.excluded-components", std::vector{}); - // cfg.set("broker.metrics.export.topic", "my/metrics/node-" + std::to_string(endpoint_nr)); - // cfg.set("broker.metrics.export.prefixes", std::vector{"caf"s,"broker"s}); - // if (endpoint_nr == 0) { + // cfg.set("broker.metrics.export.topic", "my/metrics/node-" + + // std::to_string(endpoint_nr)); cfg.set("broker.metrics.export.prefixes", + // std::vector{"caf"s,"broker"s}); if (endpoint_nr == 0) { // cfg.set("broker.metrics.import.topics", std::vector{"my/metrics"s}); // cfg.set("broker.metrics.port", 4040); // } @@ -254,10 +254,10 @@ TEST(a full mesh emits endpoint_discovered and peer_added for all nodes) { lines.emplace_back("hello from " + std::to_string(i)); hellos.emplace_back(lines); } - auto sequence - = std::vector{"endpoint_discovered"_a, "peer_added"_a, - alternative{"peer_lost", "peer_removed"}, - "endpoint_unreachable"_a}; + auto sequence = + std::vector{"endpoint_discovered"_a, "peer_added"_a, + alternative{"peer_lost", "peer_removed"}, + "endpoint_unreachable"_a}; // Check all endpoints. for (size_t index = 0; index != num_endpoints; ++index) { for (size_t i = 0; i != num_endpoints; ++i) @@ -439,7 +439,7 @@ TEST(only one put_unique may pass) { if (auto maybe_services = ep.attach_clone("zeek/known/services", 0.5); SYNC_CHECK(maybe_services)) { services = std::move(*maybe_services); - std::vectorproxies; + std::vector proxies; for (int i = 0; i < 3; ++i) { proxies.emplace_back(services); for (size_t req_id = 1; req_id < 4; ++req_id) { diff --git a/tests/cpp/system/shutdown.cc b/tests/cpp/system/shutdown.cc index 881ac103..4637d2ea 100644 --- a/tests/cpp/system/shutdown.cc +++ b/tests/cpp/system/shutdown.cc @@ -136,7 +136,7 @@ TEST(endpoints send published data before terminating) { endpoint ep{make_config(log_path_template("publish", "ep1"))}; ep.subscribe( {"/foo/bar"}, [](caf::unit_t&) {}, - [ep1_log, beacon_ptr](caf::unit_t&, data_message msg) { + [ep1_log, beacon_ptr](caf::unit_t&, data_message msg) { ep1_log->emplace_back(std::move(msg)); beacon_ptr->set_true(); }, diff --git a/tests/cpp/test.cc b/tests/cpp/test.cc index 356c3cb2..c7ca1d3f 100644 --- a/tests/cpp/test.cc +++ b/tests/cpp/test.cc @@ -38,8 +38,7 @@ normalize_status_log(const std::vector& xs, return ec::unspecified; return static_cast(err.code()); }; - std::vector - lines; + std::vector lines; lines.reserve(xs.size()); for (auto& x : xs) { if (auto err = to(get_data(x))) { @@ -259,7 +258,7 @@ void base_fixture::consume_message() { int main(int argc, char** argv) { caf::init_global_meta_objects(); endpoint::system_guard sys_guard; // Initialize global state. - //if (! broker::logger::file(broker::logger::debug, "broker-unit-test.log")) - // return 1; + // if (! broker::logger::file(broker::logger::debug, "broker-unit-test.log")) + // return 1; return caf::test::main(argc, argv); } diff --git a/tests/cpp/test.hh b/tests/cpp/test.hh index e77df7c5..aa4af04a 100644 --- a/tests/cpp/test.hh +++ b/tests/cpp/test.hh @@ -1,7 +1,7 @@ #pragma once #ifdef SUITE -#define CAF_SUITE SUITE +# define CAF_SUITE SUITE #endif #include @@ -69,7 +69,7 @@ CAF_BEGIN_TYPE_ID_BLOCK(broker_test, caf::id_block::broker::end) CAF_ADD_TYPE_ID(broker_test, (consumer_msg)) CAF_ADD_TYPE_ID(broker_test, (producer_msg)) - CAF_ADD_TYPE_ID(broker_test, (std::vector)) + CAF_ADD_TYPE_ID(broker_test, (std::vector) ) CAF_ADD_TYPE_ID(broker_test, (string_channel::consumer_message)) CAF_ADD_TYPE_ID(broker_test, (string_channel::cumulative_ack)) CAF_ADD_TYPE_ID(broker_test, (string_channel::event)) @@ -95,7 +95,6 @@ bool inspect(Inspector& f, consumer_msg& x) { f.field("content", x.content)); } - // -- synchronization ---------------------------------------------------------- // Drop-in replacement for std::barrier (based on the TS API as of 2020). @@ -327,7 +326,6 @@ T unbox(broker::expected x) { return std::move(*x); } - inline broker::data value_of(broker::expected x) { if (!x) { FAIL("cannot unbox expected: " << to_string(x.error())); @@ -337,8 +335,8 @@ inline broker::data value_of(broker::expected x) { inline broker::error error_of(broker::expected x) { if (x) { - FAIL("cannot get error of expected, contains value: " - << to_string(*x)); + FAIL( + "cannot get error of expected, contains value: " << to_string(*x)); } return std::move(x.error()); } diff --git a/tests/cpp/topic.cc b/tests/cpp/topic.cc index c92aa767..b7ef165e 100644 --- a/tests/cpp/topic.cc +++ b/tests/cpp/topic.cc @@ -10,7 +10,7 @@ namespace { auto sep = std::string{topic::sep}; -} // namespace +} // namespace TEST(concatenation) { topic t; @@ -46,23 +46,23 @@ TEST(prefix) { topic t4 = "/zeek/stores/masters/"; topic t5 = "/"; // t0 is a prefix of all topics except t5 - CHECK( t0.prefix_of(t0)); - CHECK( t0.prefix_of(t1)); - CHECK( t0.prefix_of(t2)); - CHECK( t0.prefix_of(t3)); - CHECK( t0.prefix_of(t4)); + CHECK(t0.prefix_of(t0)); + CHECK(t0.prefix_of(t1)); + CHECK(t0.prefix_of(t2)); + CHECK(t0.prefix_of(t3)); + CHECK(t0.prefix_of(t4)); CHECK(!t0.prefix_of(t5)); // t1 is a prefix of itself and t2 CHECK(!t1.prefix_of(t0)); - CHECK( t1.prefix_of(t1)); - CHECK( t1.prefix_of(t2)); + CHECK(t1.prefix_of(t1)); + CHECK(t1.prefix_of(t2)); CHECK(!t1.prefix_of(t3)); CHECK(!t1.prefix_of(t4)); CHECK(!t1.prefix_of(t5)); // t2 is only a prefix of itself CHECK(!t2.prefix_of(t0)); CHECK(!t2.prefix_of(t1)); - CHECK( t2.prefix_of(t2)); + CHECK(t2.prefix_of(t2)); CHECK(!t2.prefix_of(t3)); CHECK(!t2.prefix_of(t4)); CHECK(!t2.prefix_of(t5)); @@ -70,21 +70,21 @@ TEST(prefix) { CHECK(!t3.prefix_of(t0)); CHECK(!t3.prefix_of(t1)); CHECK(!t3.prefix_of(t2)); - CHECK( t3.prefix_of(t3)); - CHECK( t3.prefix_of(t4)); + CHECK(t3.prefix_of(t3)); + CHECK(t3.prefix_of(t4)); CHECK(!t3.prefix_of(t5)); // t4 is only a prefix of itself CHECK(!t4.prefix_of(t0)); CHECK(!t4.prefix_of(t1)); CHECK(!t4.prefix_of(t2)); CHECK(!t4.prefix_of(t3)); - CHECK( t4.prefix_of(t4)); + CHECK(t4.prefix_of(t4)); CHECK(!t4.prefix_of(t5)); // t5 is a prefix of all topics - CHECK( t5.prefix_of(t0)); - CHECK( t5.prefix_of(t1)); - CHECK( t5.prefix_of(t2)); - CHECK( t5.prefix_of(t3)); - CHECK( t5.prefix_of(t4)); - CHECK( t5.prefix_of(t5)); + CHECK(t5.prefix_of(t0)); + CHECK(t5.prefix_of(t1)); + CHECK(t5.prefix_of(t2)); + CHECK(t5.prefix_of(t3)); + CHECK(t5.prefix_of(t4)); + CHECK(t5.prefix_of(t5)); } diff --git a/tests/micro-benchmark/include/main.hh b/tests/micro-benchmark/include/main.hh index 079e6f9a..221ba127 100644 --- a/tests/micro-benchmark/include/main.hh +++ b/tests/micro-benchmark/include/main.hh @@ -22,8 +22,8 @@ class uuid_multipath; class uuid_multipath_group; class uuid_multipath_node; -using node_message_content - = broker::variant; +using node_message_content = + broker::variant; using uuid_node_message = caf::cow_tuple; @@ -33,12 +33,12 @@ using uuid_node_message = caf::cow_tuple; CAF_BEGIN_TYPE_ID_BLOCK(micro_benchmarks, caf::id_block::broker::end) - MICRO_BENCH_ADD_TYPE((caf::stream)) + MICRO_BENCH_ADD_TYPE((caf::stream) ) MICRO_BENCH_ADD_TYPE((legacy_node_message)) - MICRO_BENCH_ADD_TYPE((std::vector)) + MICRO_BENCH_ADD_TYPE((std::vector) ) - MICRO_BENCH_ADD_TYPE((caf::stream)) - MICRO_BENCH_ADD_TYPE((std::vector)) + MICRO_BENCH_ADD_TYPE((caf::stream) ) + MICRO_BENCH_ADD_TYPE((std::vector) ) MICRO_BENCH_ADD_TYPE((uuid_multipath)) MICRO_BENCH_ADD_TYPE((uuid_node_message)) @@ -48,7 +48,6 @@ CAF_END_TYPE_ID_BLOCK(micro_benchmarks) /// A `node_message` as it used to be pre-ALM. struct legacy_node_message { - /// Content of the message. node_message_content content; @@ -133,7 +132,6 @@ private: uuid_multipath_node* first_ = nullptr; }; - class uuid_multipath_node { public: friend class uuid_multipath; @@ -209,7 +207,8 @@ private: size_t n = 0; if (f.begin_sequence(n)) { for (size_t i = 0; i < n; ++i) { - auto child = broker::detail::new_instance(mem, uuid{}, false); + auto child = + broker::detail::new_instance(mem, uuid{}, false); if (!child->load(mem, f)) { return false; } else if (!down_.emplace(child)) { diff --git a/tests/micro-benchmark/src/main.cc b/tests/micro-benchmark/src/main.cc index c0c72d53..96749e2e 100644 --- a/tests/micro-benchmark/src/main.cc +++ b/tests/micro-benchmark/src/main.cc @@ -15,7 +15,8 @@ using namespace std::literals; // -- custom types ------------------------------------------------------------- uuid_multipath_tree::uuid_multipath_tree(uuid id, bool is_receiver) { - root = broker::detail::new_instance(mem, id, is_receiver); + root = broker::detail::new_instance(mem, id, + is_receiver); } uuid_multipath_tree::~uuid_multipath_tree() { @@ -26,8 +27,8 @@ uuid_multipath_group::~uuid_multipath_group() { delete first_; } -bool -uuid_multipath_group::equals(const uuid_multipath_group& other) const noexcept { +bool uuid_multipath_group::equals( + const uuid_multipath_group& other) const noexcept { auto eq = [](const auto& lhs, const auto& rhs) { return lhs.equals(rhs); }; return std::equal(begin(), end(), other.begin(), other.end(), eq); } @@ -101,8 +102,8 @@ uuid_multipath_node::~uuid_multipath_node() { delete right_; } -bool -uuid_multipath_node::equals(const uuid_multipath_node& other) const noexcept { +bool uuid_multipath_node::equals( + const uuid_multipath_node& other) const noexcept { return id_ == other.id_ && down_.equals(other.down_); } @@ -189,10 +190,9 @@ caf::uuid generator::next_uuid() { } std::string generator::next_string(size_t length) { - std::string_view charset - = "0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; + std::string_view charset = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"; std::uniform_int_distribution d{0, charset.size() - 1}; std::string result; result.resize(length); diff --git a/tests/micro-benchmark/src/routing-table.cc b/tests/micro-benchmark/src/routing-table.cc index 787eb99d..3a2cec10 100644 --- a/tests/micro-benchmark/src/routing-table.cc +++ b/tests/micro-benchmark/src/routing-table.cc @@ -28,7 +28,8 @@ struct linear_routing_table_row { linear_routing_table_row(linear_routing_table_row&&) = default; linear_routing_table_row(const linear_routing_table_row&) = default; linear_routing_table_row& operator=(linear_routing_table_row&&) = default; - linear_routing_table_row& operator=(const linear_routing_table_row&) = default; + linear_routing_table_row& + operator=(const linear_routing_table_row&) = default; explicit linear_routing_table_row(endpoint_id id) : id(std::move(id)) { versioned_paths.reserve(32); @@ -207,7 +208,7 @@ class routing_table : public benchmark::Fixture { routing_table() { topologies.resize(10); - //v2_topologies.resize(10); + // v2_topologies.resize(10); ids.resize(10); receivers_10p.resize(10); id_generator g; @@ -216,9 +217,9 @@ class routing_table : public benchmark::Fixture { }; for (size_t index = 0; index < 10; ++index) fill_tbl(topologies[index], g, {}, 0, index, on_new_node); - // for (size_t index = 0; index < 10; ++index) - // fill_tbl(v2_topologies[index], g, {}, 0, index, [](auto&&...) {}); - // Sanity checking + // for (size_t index = 0; index < 10; ++index) + // fill_tbl(v2_topologies[index], g, {}, 0, index, [](auto&&...) {}); + // Sanity checking #ifndef NDEBUG for (size_t index = 0; index < 10; ++index) assert(ids[index].size() == (1 << (index + 1))); diff --git a/tests/micro-benchmark/src/serialization.cc b/tests/micro-benchmark/src/serialization.cc index bc394a7b..ce5e4873 100644 --- a/tests/micro-benchmark/src/serialization.cc +++ b/tests/micro-benchmark/src/serialization.cc @@ -171,14 +171,18 @@ BENCHMARK_REGISTER_F(serialization, load_node_message)->DenseRange(0, 2, 1); // -- saving and loading legacy node messages ---------------------------------- -BENCHMARK_DEFINE_F(serialization, save_legacy_node_message)(benchmark::State& state) { +BENCHMARK_DEFINE_F(serialization, save_legacy_node_message) +(benchmark::State& state) { run_serialization_bench(state); } -BENCHMARK_REGISTER_F(serialization, save_legacy_node_message)->DenseRange(0, 2, 1); +BENCHMARK_REGISTER_F(serialization, save_legacy_node_message) + ->DenseRange(0, 2, 1); -BENCHMARK_DEFINE_F(serialization, load_legacy_node_message)(benchmark::State& state) { +BENCHMARK_DEFINE_F(serialization, load_legacy_node_message) +(benchmark::State& state) { run_deserialization_bench(state); } -BENCHMARK_REGISTER_F(serialization, load_legacy_node_message)->DenseRange(0, 2, 1); +BENCHMARK_REGISTER_F(serialization, load_legacy_node_message) + ->DenseRange(0, 2, 1);