Files
scylladb/utils/exception_container.hh
Kefu Chai 168ade72f8 treewide: replace formatter<std::string_view> with formatter<string_view>
in in {fmt} before v10, it provides the specialization of `fmt::formatter<..>`
for `std::string_view` as well as the specialization of `fmt::formatter<..>`
for `fmt::string_view` which is an implementation builtin in {fmt} for
compatibility of pre-C++17. and this type is used even if the code is
compiled with C++ stadandard greater or equal to C++17. also, before v10,
the `fmt::formatter<std::string_view>::format()` is defined so it accepts
`std::string_view`. after v10, `fmt::formatter<std::string_view>` still
exists, but it is now defined using `format_as()` machinery, so it's
`format()` method does not actually accept `std::string_view`, it
accepts `fmt::string_view`, as the former can be converted to
`fmt::string_view`.

this is why we can inherit from `fmt::formatter<std::string_view>` and
use `formatter<std::string_view>::format(foo, ctx);` to implement the
`format()` method with {fmt} v9, but we cannot do this with {fmt} v10,
and we would have following compilation failure:

```
FAILED: service/CMakeFiles/service.dir/RelWithDebInfo/topology_state_machine.cc.o
/home/kefu/.local/bin/clang++ -DFMT_DEPRECATED_OSTREAM -DFMT_SHARED -DSCYLLA_BUILD_MODE=release -DSEASTAR_API_LEVEL=7 -DSEASTAR_LOGGER_COMPILE_TIME_FMT -DSEASTAR_LOGGER_TYPE_STDOUT -DSEASTAR_SCHEDULING_GROUPS_COUNT=16 -DSEASTAR_SSTRING -DXXH_PRIVATE_API -DCMAKE_INTDIR=\"RelWithDebInfo\" -I/home/kefu/dev/scylladb -I/home/kefu/dev/scylladb/build/gen -I/home/kefu/dev/scylladb/seastar/include -I/home/kefu/dev/scylladb/build/seastar/gen/include -I/home/kefu/dev/scylladb/build/seastar/gen/src -ffunction-sections -fdata-sections -O3 -g -gz -std=gnu++20 -fvisibility=hidden -Wall -Werror -Wextra -Wno-error=deprecated-declarations -Wimplicit-fallthrough -Wno-c++11-narrowing -Wno-deprecated-copy -Wno-mismatched-tags -Wno-missing-field-initializers -Wno-overloaded-virtual -Wno-unsupported-friend -Wno-enum-constexpr-conversion -Wno-unused-parameter -ffile-prefix-map=/home/kefu/dev/scylladb=. -march=westmere -mllvm -inline-threshold=2500 -fno-slp-vectorize -U_FORTIFY_SOURCE -Werror=unused-result -MD -MT service/CMakeFiles/service.dir/RelWithDebInfo/topology_state_machine.cc.o -MF service/CMakeFiles/service.dir/RelWithDebInfo/topology_state_machine.cc.o.d -o service/CMakeFiles/service.dir/RelWithDebInfo/topology_state_machine.cc.o -c /home/kefu/dev/scylladb/service/topology_state_machine.cc
/home/kefu/dev/scylladb/service/topology_state_machine.cc:254:41: error: no matching member function for call to 'format'
  254 |     return formatter<std::string_view>::format(it->second, ctx);
      |            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~
/usr/include/fmt/core.h:2759:22: note: candidate function template not viable: no known conversion from 'seastar::basic_sstring<char, unsigned int, 15>' to 'const fmt::basic_string_view<char>' for 1st argument
 2759 |   FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const
      |                      ^      ~~~~~~~~~~~~
```

because the inherited `format()` method actually comes from
`fmt::formatter<fmt::string_view>`. to reduce the confusion, in this
change, we just inherit from `fmt::format<string_view>`, where
`string_view` is actually `fmt::string_view`. this follows
the document at
https://fmt.dev/latest/api.html#formatting-user-defined-types,
and since there is less indirection under the hood -- we do not
use the specialization created by `FMT_FORMAT_AS` which inherit
from `formatter<fmt::string_view>`, hopefully this can improve
the compilation speed a little bit. also, this change addresses
the build failure with {fmt} v10.

Signed-off-by: Kefu Chai <kefu.chai@scylladb.com>

Closes scylladb/scylladb#18299
2024-04-19 07:44:07 +03:00

172 lines
5.7 KiB
C++

/*
* Copyright 2022-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#pragma once
#include <exception>
#include <typeinfo>
#include <type_traits>
#include <memory>
#include <ostream>
#include <variant>
#include <seastar/core/future.hh>
#include <seastar/core/distributed.hh>
#include <seastar/util/log.hh>
#include "utils/variant_element.hh"
namespace utils {
class bad_exception_container_access : public std::exception {
public:
const char* what() const noexcept override {
return "bad exception container access";
}
};
// A variant-like type capable of holding one of the allowed exception types.
// This allows inspecting the exception in the error handling code without
// having to resort to costly rethrowing of std::exception_ptr, as is
// in the case of the usual exception handling.
//
// It's not as ergonomic as using exceptions with seastar, but allows for
// fast inspection and manipulation.
//
// The exception is held behind a std::shared_ptr. In order to minimize use
// of atomic operations, the copy constructor is deleted and copying is only
// possible by using the `clone()` method.
//
// This means that the moved-out exception container becomes "empty" and
// does not contain a valid exception.
template<typename... Exs>
struct exception_container {
private:
using exception_variant = std::variant<Exs...>;
// TODO: Idea for a possible improvement: get rid of the variant
// and just store a pointer to an error allocated on the heap.
// Keep an integer which identifies the variant.
// Bonus points: if each error type has a unique, globally-assigned
// identified integer, then conversion of the exception_container
// to a container supporting a superset of errors becomes very cheap.
std::shared_ptr<exception_variant> _eptr;
// Users should use `clone()` in order to copy the exception container.
// The copy constructor is made private in order to make copying explicit.
exception_container(const exception_container&) = default;
void check_nonempty() const {
if (empty()) {
throw bad_exception_container_access();
}
}
public:
// Constructs an exception_container which does not contain any exception.
exception_container() = default;
exception_container(exception_container&&) = default;
exception_container& operator=(exception_container&&) = default;
exception_container& operator=(const exception_container&) = delete; // Must be explicitly copied with `clone()`
template<typename Ex>
requires VariantElement<Ex, exception_variant>
exception_container(Ex&& ex)
: _eptr(std::make_shared<exception_variant>(std::forward<Ex>(ex)))
{ }
inline bool empty() const {
return __builtin_expect(!_eptr, false);
}
inline operator bool() const {
return !empty();
}
// Accepts a visitor.
// If the container is empty, the visitor is called with
// a bad_exception_container_access.
auto accept(auto f) const {
if (empty()) {
return f(bad_exception_container_access());
}
return std::visit(std::move(f), *_eptr);
}
// Explicitly clones the exception container.
exception_container clone() const noexcept {
return exception_container(*this);
}
// Throws currently held exception as a C++ exception.
// If the container is empty, it throws bad_exception_container_access.
[[noreturn]] void throw_me() const {
check_nonempty();
std::visit([] (const auto& ex) { throw ex; }, *_eptr);
std::terminate(); // Should be unreachable
}
// Creates an exceptional future from this error.
// The exception is copied into the new exceptional future.
// If the container is empty, returns an exceptional future
// with the bad_exception_container_access exception.
template<typename T = void>
seastar::future<T> as_exception_future() const & {
if (!_eptr) {
return seastar::make_exception_future<T>(bad_exception_container_access());
}
return std::visit([] (const auto& ex) {
return seastar::make_exception_future<T>(ex);
}, *_eptr);
}
// Transforms this exception future into an exceptional future.
// The exception is moved out and the container becomes empty.
// If the container was empty, returns an exceptional future
// with the bad_exception_container_access exception.
template<typename T = void>
seastar::future<T> into_exception_future() && {
if (!_eptr) {
return seastar::make_exception_future<T>(bad_exception_container_access());
}
auto f = std::visit([] (auto&& ex) {
return seastar::make_exception_future<T>(std::move(ex));
}, *_eptr);
_eptr.reset();
return f;
}
};
template<typename T>
struct is_exception_container : std::false_type {};
template<typename... Exs>
struct is_exception_container<exception_container<Exs...>> : std::true_type {};
template<typename T>
concept ExceptionContainer = is_exception_container<T>::value;
}
#if FMT_VERSION < 100000
// fmt v10 introduced formatter for std::exception
template <>
struct fmt::formatter<utils::bad_exception_container_access> : fmt::formatter<string_view> {
auto format(const utils::bad_exception_container_access& e, fmt::format_context& ctx) const {
return fmt::format_to(ctx.out(), "{}", e.what());
}
};
#endif
template <typename... Exs> struct fmt::formatter<utils::exception_container<Exs...>> : fmt::formatter<string_view> {
auto format(const auto& ec, fmt::format_context& ctx) const {
auto out = ctx.out();
ec.accept([&out] (const auto& ex) { out = fmt::format_to(out, "{}", ex); });
return out;
}
};