Files
Library/include/Void/Functional/Error.hpp
T

308 lines
9.0 KiB
C++

#pragma once
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
#include <vector>
namespace Void::Result
{
/// Machine-readable classification shared across Void modules (C-02).
enum class ErrorKind : std::uint8_t {
invalid_argument = 0,
not_found,
conflict,
cancelled,
timeout,
overloaded,
unsupported,
io,
corrupt,
exhausted,
internal
};
[[nodiscard]] constexpr std::string_view
to_string(ErrorKind kind) noexcept
{
switch (kind) {
case ErrorKind::invalid_argument: return "invalid_argument";
case ErrorKind::not_found: return "not_found";
case ErrorKind::conflict: return "conflict";
case ErrorKind::cancelled: return "cancelled";
case ErrorKind::timeout: return "timeout";
case ErrorKind::overloaded: return "overloaded";
case ErrorKind::unsupported: return "unsupported";
case ErrorKind::io: return "io";
case ErrorKind::corrupt: return "corrupt";
case ErrorKind::exhausted: return "exhausted";
case ErrorKind::internal: return "internal";
}
return "internal";
}
/// Explicit module error-domain identifiers. Domain 0 is reserved for
/// generic cross-module status values; domains are never assigned by
/// hashing type names.
inline constexpr std::uint32_t kGenericErrorDomain = 0;
inline constexpr std::uint32_t kCoreErrorDomain = 1;
inline constexpr std::uint32_t kMemoryErrorDomain = 2;
inline constexpr std::uint32_t kMathErrorDomain = 3;
inline constexpr std::uint32_t kTimeErrorDomain = 4;
inline constexpr std::uint32_t kBinaryErrorDomain = 5;
inline constexpr std::uint32_t kDataErrorDomain = 6;
inline constexpr std::uint32_t kAsyncErrorDomain = 7;
inline constexpr std::uint32_t kIoErrorDomain = 8;
inline constexpr std::uint32_t kStorageErrorDomain = 9;
inline constexpr std::uint32_t kSystemErrorDomain = 10;
inline constexpr std::uint32_t kRuntimeErrorDomain = 11;
inline constexpr std::uint32_t kLogErrorDomain = 12;
inline constexpr std::uint32_t kStacktraceErrorDomain = 13;
inline constexpr std::uint32_t kObservabilityErrorDomain = 14;
inline constexpr std::uint32_t kResilienceErrorDomain = 15;
inline constexpr std::uint32_t kIpcErrorDomain = 16;
inline constexpr std::uint32_t kArchiveErrorDomain = 17;
inline constexpr std::uint32_t kCryptoErrorDomain = 18;
inline constexpr std::uint32_t kSecurityErrorDomain = 19;
inline constexpr std::uint32_t kUpdateErrorDomain = 20;
inline constexpr std::uint32_t kSqliteErrorDomain = 21;
struct ErrorCode {
std::uint32_t domain{kGenericErrorDomain};
std::int32_t value{0};
[[nodiscard]] constexpr bool
operator==(const ErrorCode&) const noexcept = default;
};
/// Compact, allocation-free failure descriptor suitable for low-memory and
/// Memory-layer error paths.
struct Status {
ErrorKind kind{ErrorKind::internal};
ErrorCode code{};
[[nodiscard]] constexpr bool
operator==(const Status&) const noexcept = default;
};
inline constexpr std::size_t kDefaultMaxErrorFrames = 16;
inline constexpr std::size_t kDefaultMaxErrorMessageBytes = 1024;
inline constexpr std::size_t kDefaultMaxFormattedErrorBytes = 16 * 1024;
namespace Detail
{
inline void bound_message(std::string& msg, bool& truncated) noexcept
{
constexpr std::string_view suffix = "...[truncated]";
if (msg.size() <= kDefaultMaxErrorMessageBytes) {
return;
}
truncated = true;
const std::size_t keep =
kDefaultMaxErrorMessageBytes > suffix.size()
? kDefaultMaxErrorMessageBytes - suffix.size()
: 0;
msg.resize(keep);
try {
msg.append(suffix);
} catch (...) {
// Preserve noexcept guarantee on bounded shrink.
}
}
} // namespace Detail
/// Default error type for Void::Result::Result<T, E>.
///
/// An Error carries a machine-readable `Status`, an optional
/// `std::error_code`, a bounded human-readable `message`, and an optional
/// shared immutable `cause` chain capped at `kDefaultMaxErrorFrames` (16).
/// Constructing from `Status` performs zero heap allocations.
class Error
{
public:
Error() noexcept = default;
explicit Error(Status status) noexcept : m_status(status) {}
Error(Status status, std::string message,
std::error_code sys = {}) noexcept
: m_status(status), m_system_code(sys),
m_message(std::move(message))
{
Detail::bound_message(m_message, m_truncated);
}
Error(ErrorKind kind, std::string message, ErrorCode code = {},
std::error_code sys = {}) noexcept
: Error(Status{kind, code}, std::move(message), sys)
{
}
explicit Error(std::string message) noexcept
: m_message(std::move(message))
{
Detail::bound_message(m_message, m_truncated);
}
Error(std::string message, Error cause)
: m_status(cause.m_status), m_system_code(cause.m_system_code),
m_message(std::move(message)), m_truncated(cause.m_truncated)
{
Detail::bound_message(m_message, m_truncated);
if (cause.m_depth < kDefaultMaxErrorFrames) {
m_depth = cause.m_depth + 1;
m_cause = std::make_shared<Error>(std::move(cause));
return;
}
// Exceeded frame budget: keep newest intermediate frames and
// pin the root frame at the tail so root classification/context
// is never lost.
std::vector<const Error*> chain;
chain.reserve(cause.m_depth);
for (const Error* cur = &cause; cur != nullptr;
cur = cur->m_cause.get()) {
chain.push_back(cur);
}
m_truncated = true;
std::shared_ptr<Error> tail =
std::make_shared<Error>(Error{*chain.back(), true});
const std::size_t keep_middle =
kDefaultMaxErrorFrames >= 2 ? kDefaultMaxErrorFrames - 2 : 0;
const std::size_t available_middle =
chain.size() > 1 ? chain.size() - 1 : 0;
const std::size_t take = std::min(keep_middle, available_middle);
for (std::size_t idx = take; idx > 0; --idx) {
auto node = std::make_shared<Error>(
Error{*chain[idx - 1], true});
node->m_cause = tail;
node->m_depth = tail->m_depth + 1;
node->m_truncated = true;
tail = std::move(node);
}
m_cause = std::move(tail);
m_depth = m_cause->m_depth + 1;
}
Error(const Error&) = default;
Error(Error&&) noexcept = default;
Error& operator=(const Error&) = default;
Error& operator=(Error&&) noexcept = default;
~Error() noexcept
{
std::shared_ptr<const Error> cur = std::move(m_cause);
while (cur && cur.use_count() == 1) {
auto mutable_cur = std::const_pointer_cast<Error>(cur);
auto next = std::move(mutable_cur->m_cause);
cur = std::move(next);
}
}
[[nodiscard]] Status status() const noexcept { return m_status; }
[[nodiscard]] ErrorKind kind() const noexcept
{
return m_status.kind;
}
[[nodiscard]] ErrorCode code() const noexcept
{
return m_status.code;
}
[[nodiscard]] std::error_code system_code() const noexcept
{
return m_system_code;
}
[[nodiscard]] std::size_t depth() const noexcept { return m_depth; }
[[nodiscard]] bool truncated() const noexcept
{
return m_truncated;
}
[[nodiscard]] const std::string& message() const noexcept
{
return m_message;
}
[[nodiscard]] const std::shared_ptr<const Error>&
cause() const noexcept
{
return m_cause;
}
/// Returns a new Error whose message is `ctx` and whose cause
/// is *this, preserving root Status and system_code.
[[nodiscard]] Error with_context(std::string ctx) const&
{
return Error{std::move(ctx), *this};
}
[[nodiscard]] Error with_context(std::string ctx) &&
{
return Error{std::move(ctx), std::move(*this)};
}
/// Render the cause chain as
/// "outer\n caused by: middle\n caused by: inner"
/// bounded by `kDefaultMaxFormattedErrorBytes`.
[[nodiscard]] std::string format() const
{
std::string out =
m_message.empty() ? std::string{to_string(m_status.kind)}
: m_message;
const Error* cur = m_cause.get();
while (cur != nullptr) {
out += "\n caused by: ";
out += cur->m_message.empty()
? to_string(cur->m_status.kind)
: std::string_view{cur->m_message};
if (out.size() >= kDefaultMaxFormattedErrorBytes) {
break;
}
cur = cur->m_cause.get();
}
if (m_truncated) {
out += "\n [truncated: diagnostic limits applied]";
}
if (out.size() > kDefaultMaxFormattedErrorBytes) {
constexpr std::string_view suffix = "\n...[truncated]";
const std::size_t keep =
kDefaultMaxFormattedErrorBytes > suffix.size()
? kDefaultMaxFormattedErrorBytes - suffix.size()
: 0;
out.resize(keep);
out.append(suffix);
}
return out;
}
private:
Error(const Error& other, bool /*detach_cause*/)
: m_status(other.m_status), m_system_code(other.m_system_code),
m_message(other.m_message), m_depth(1),
m_truncated(other.m_truncated)
{
}
Status m_status{};
std::error_code m_system_code{};
std::string m_message;
std::shared_ptr<const Error> m_cause;
std::size_t m_depth{1};
bool m_truncated{false};
};
} // namespace Void::Result