Files
Library/include/Void/Configuration/Config.hpp
T
faumarayandClaude Opus 4.8 80293ee56f Add async/resilience/reflection primitives + FSM v2 rewrite
A round of new universal capabilities (all generic — templated/reflection
based, no app coupling), verified by the test suite (1103 passing):

Data reflection:
- Reflect.hpp now (de)serializes chrono::duration, chrono::time_point,
  std::variant (tagged), std::array, and non-string-keyed std::map;
  Meta.hpp gains is_time_point_v et al.

Async:
- EventBus gains Mode::Async (worker-thread dispatch + flush()).
- ThreadPool gains a bounded queue, try_submit(), and rejection stats.

New modules / containers:
- Resilience: TokenBucket, KeyedRateLimiter<Key>, CircuitBreaker,
  ResourceMonitor.
- Containers: BufferPool<T> (size-class buffer reuse) and Cache<K,V>
  (per-entry TTL, LRU/LFU/FIFO eviction, hit/miss stats).
- System: process/CPU/memory metrics (Metrics.hpp) and a streaming
  Process API.

Plus FSM v2 (typed Success/Failure, sub-machines, parallel regions,
history states, deferred events), Configuration/Logging reflection
helpers, and the accompanying test suites.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 15:45:16 +03:00

548 lines
18 KiB
C++

#pragma once
#include <Void/Configuration/Env.hpp>
#include <Void/Data/Ini.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Detail/Enum.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/Time/Format.hpp>
#include <algorithm>
#include <cctype>
#include <charconv>
#include <chrono>
#include <cstdint>
#include <filesystem>
#include <format>
#include <initializer_list>
#include <optional>
#include <sstream>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <vector>
#if defined(__unix__) || defined(__APPLE__)
extern char** environ; // NOLINT
#define VOID_CONFIG_HAS_ENVIRON 1
#endif
namespace Void::Configuration
{
/// Layered key-value configuration store with dotted nested keys.
///
/// Values are plain strings; typed access via get_as<T>(). Layers are
/// applied via overlay(): the last overlay wins on key conflicts.
/// Typical usage:
///
/// auto cfg = Config::from_env_prefix("MYAPP_"); // MYAPP_LOG__LEVEL →
/// log.level if (auto r = Config::from_ini("app.ini"); r.has_value())
/// cfg.overlay(*r); // ini overrides env
/// cfg.overlay(Config::from_args(argc, argv)); // --log.level=debug
/// wins auto level = cfg.get_or("log.level", "info"); auto retries =
/// cfg.get_as<int>("net.retries"); // Result<int>
///
/// Sources: from_env / from_env_prefix (environment), from_file
/// (KEY=VALUE), from_ini (sections become key prefixes), from_json
/// (nested objects flatten into dotted keys), from_args (--key=value).
class Config
{
public:
Config() = default;
/// Populate from specific named environment variables.
/// Keys absent from the environment are silently skipped.
[[nodiscard]] static Config
from_env(std::initializer_list<std::string_view> keys)
{
Config cfg;
for (auto key : keys) {
if (auto r = get_env(key); r.has_value()) {
cfg.values_.emplace(std::string{key}, std::move(*r));
Void::Log::debug("Configuration",
"from_env: loaded '{}'", key);
}
}
return cfg;
}
/// Parse a KEY=VALUE text file (one pair per line, # for comments).
/// Lines without '=' produce a warning log and are skipped.
[[nodiscard]] static Void::Result::Result<Config,
Void::Result::Error>
from_file(const std::filesystem::path& path)
{
auto text = Void::FileSystem::read_file(path);
if (!text.has_value()) {
return Void::Result::fail(
std::format("Configuration::Config::from_file: {}",
text.error().message()));
}
Config cfg;
std::istringstream ss{*text};
std::string line;
int lineno = 0;
while (std::getline(ss, line)) {
++lineno;
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
std::string_view sv{line};
while (!sv.empty() && sv.front() == ' ') {
sv.remove_prefix(1);
}
if (sv.empty() || sv.front() == '#') {
continue;
}
auto eq = sv.find('=');
if (eq == std::string_view::npos) {
Void::Log::warn("Configuration",
"from_file: '{}' line {}: missing '='",
path.string(), lineno);
continue;
}
auto key = sv.substr(0, eq);
while (!key.empty() && key.back() == ' ') {
key.remove_suffix(1);
}
auto val = sv.substr(eq + 1);
cfg.values_.emplace(std::string{key}, std::string{val});
}
Void::Log::debug("Configuration",
"from_file: loaded {} keys from '{}'",
cfg.values_.size(), path.string());
return Void::Result::ok(std::move(cfg));
}
/// Layer `other` on top: other's values win on key conflicts.
void overlay(const Config& other)
{
for (const auto& [k, v] : other.values_) {
values_.insert_or_assign(k, v);
}
}
/// Explicit per-key override (highest priority).
void set(std::string_view key, std::string value)
{
values_.insert_or_assign(std::string{key}, std::move(value));
}
/// Look up a key. Returns an error if the key is not present.
[[nodiscard]] Void::Result::Result<std::string_view,
Void::Result::Error>
get(std::string_view key) const
{
auto it = values_.find(std::string{key});
if (it == values_.end()) {
return Void::Result::fail(std::format(
"Configuration::Config::get: key '{}' not found", key));
}
return Void::Result::ok(std::string_view{it->second});
}
/// Look up a key, returning `fallback` when the key is absent.
[[nodiscard]] std::string_view
get_or(std::string_view key,
std::string_view fallback = {}) const
{
auto it = values_.find(std::string{key});
return it != values_.end() ? std::string_view{it->second}
: fallback;
}
[[nodiscard]] std::size_t size() const noexcept
{
return values_.size();
}
[[nodiscard]] bool empty() const noexcept
{
return values_.empty();
}
// ═════════════════════════════════════════════════════════════════
// Additional sources
// ═════════════════════════════════════════════════════════════════
/// Scan the whole environment for variables starting with `prefix`.
/// The prefix is stripped, `__` becomes `.`, and the key is
/// lowercased: MYAPP_LOG__LEVEL=debug → log.level=debug.
[[nodiscard]] static Config from_env_prefix(std::string_view prefix)
{
Config cfg;
#ifdef VOID_CONFIG_HAS_ENVIRON
for (char** env = environ; *env != nullptr; ++env) {
const std::string_view kv{*env};
const auto eq = kv.find('=');
if (eq == std::string_view::npos ||
!kv.starts_with(prefix)) {
continue;
}
auto raw_key = kv.substr(prefix.size(), eq - prefix.size());
std::string key;
key.reserve(raw_key.size());
for (std::size_t i = 0; i < raw_key.size(); ++i) {
if (raw_key[i] == '_' && i + 1 < raw_key.size() &&
raw_key[i + 1] == '_') {
key += '.';
++i;
} else {
key += static_cast<char>(std::tolower(
static_cast<unsigned char>(raw_key[i])));
}
}
cfg.values_.emplace(std::move(key),
std::string{kv.substr(eq + 1)});
}
Void::Log::debug("Configuration",
"from_env_prefix('{}'): {} keys", prefix,
cfg.size());
#else
(void)prefix;
#endif
return cfg;
}
/// Parse an INI file: `[section]` + `key = value` becomes
/// "section.key"; pairs before any section keep their bare key.
[[nodiscard]] static Void::Result::Result<Config,
Void::Result::Error>
from_ini(const std::filesystem::path& path)
{
auto text = Void::FileSystem::read_file(path);
if (!text.has_value()) {
return Void::Result::fail(
std::format("Configuration::Config::from_ini: {}",
text.error().message()));
}
return from_ini_text(*text);
}
[[nodiscard]] static Void::Result::Result<Config,
Void::Result::Error>
from_ini_text(std::string_view text)
{
Void::Ini::IniFile ini;
if (auto err = Void::Ini::IniFile::parse(ini, text);
err.has_value()) {
return Void::Result::fail(std::format(
"Configuration::Config::from_ini: line {}: {}",
err->line, err->message));
}
Config cfg;
for (const auto& name : ini.sections()) {
const auto* section = ini.section(name);
if (section == nullptr) {
continue;
}
for (const auto& [key, value] : *section) {
auto full = name.empty() ? key : name + "." + key;
cfg.values_.insert_or_assign(std::move(full), value);
}
}
return Void::Result::ok(std::move(cfg));
}
/// Parse a JSON file; nested objects flatten into dotted keys,
/// arrays into numeric segments ("servers.0.host"). Scalars are
/// stored in their canonical string form.
[[nodiscard]] static Void::Result::Result<Config,
Void::Result::Error>
from_json(const std::filesystem::path& path)
{
auto text = Void::FileSystem::read_file(path);
if (!text.has_value()) {
return Void::Result::fail(
std::format("Configuration::Config::from_json: {}",
text.error().message()));
}
return from_json_text(*text);
}
[[nodiscard]] static Void::Result::Result<Config,
Void::Result::Error>
from_json_text(std::string_view text)
{
auto parsed = Void::Json::parse(text);
if (!parsed.has_value()) {
return Void::Result::fail(std::format(
"Configuration::Config::from_json: line {} col {}: {}",
parsed.error().line, parsed.error().col,
parsed.error().message));
}
Config cfg;
flatten_json(cfg, "", *parsed);
return Void::Result::ok(std::move(cfg));
}
/// Collect `--key=value`, `--key value` and bare `--flag`
/// (stored as "true") arguments. Non-option arguments are ignored.
[[nodiscard]] static Config from_args(int argc,
const char* const* argv)
{
Config cfg;
for (int i = 1; i < argc; ++i) {
const std::string_view arg{argv[i]};
if (!arg.starts_with("--") || arg.size() <= 2) {
continue;
}
const auto body = arg.substr(2);
if (const auto eq = body.find('=');
eq != std::string_view::npos) {
cfg.values_.insert_or_assign(
std::string{body.substr(0, eq)},
std::string{body.substr(eq + 1)});
} else if (i + 1 < argc &&
std::string_view{argv[i + 1]}.substr(0, 2) !=
"--") {
cfg.values_.insert_or_assign(std::string{body},
std::string{argv[i + 1]});
++i;
} else {
cfg.values_.insert_or_assign(std::string{body}, "true");
}
}
return cfg;
}
// ═════════════════════════════════════════════════════════════════
// Typed access
// ═════════════════════════════════════════════════════════════════
/// Look up and convert. Supported T: integral and floating types,
/// bool ("true/false/1/0/yes/no/on/off", case-insensitive), enums
/// (by enumerator name, reflection builds), std::string, and
/// std::chrono durations ("250ms", "10s", "5m", "1h", "500us",
/// "30ns" — converted to T, rejecting lossy narrowing).
template <typename T>
[[nodiscard]] Void::Result::Result<T, Void::Result::Error>
get_as(std::string_view key) const
{
const auto it = values_.find(std::string{key});
if (it == values_.end()) {
return Void::Result::fail(std::format(
"Configuration::Config::get_as: key '{}' not found",
key));
}
return convert<T>(key, it->second);
}
/// Typed lookup with fallback for missing keys. Conversion errors
/// on a *present* key still surface the fallback but are logged.
template <typename T>
[[nodiscard]] T get_or_as(std::string_view key, T fallback) const
{
auto r = get_as<T>(key);
if (r.has_value()) {
return std::move(*r);
}
return fallback;
}
// ═════════════════════════════════════════════════════════════════
// Key enumeration / subtrees
// ═════════════════════════════════════════════════════════════════
/// All keys, sorted.
[[nodiscard]] std::vector<std::string> keys() const
{
std::vector<std::string> out;
out.reserve(values_.size());
for (const auto& [k, _] : values_) {
out.push_back(k);
}
std::sort(out.begin(), out.end());
return out;
}
/// A new Config holding every key under "prefix." with the prefix
/// stripped: subtree("log") of {log.level, log.file.path} yields
/// {level, file.path}.
[[nodiscard]] Config subtree(std::string_view prefix) const
{
Config out;
const auto full = std::string{prefix} + ".";
for (const auto& [k, v] : values_) {
if (k.starts_with(full)) {
out.values_.emplace(k.substr(full.size()), v);
}
}
return out;
}
[[nodiscard]] bool contains(std::string_view key) const
{
return values_.contains(std::string{key});
}
private:
static void flatten_json(Config& cfg, const std::string& prefix,
const Void::Json::Value& v)
{
using Void::Json::Value;
if (v.is_object()) {
for (const auto& [k, child] : v.as_object()) {
flatten_json(cfg, prefix.empty() ? k : prefix + "." + k,
child);
}
} else if (v.is_array()) {
std::size_t i = 0;
for (const auto& child : v.as_array()) {
flatten_json(cfg, prefix + "." + std::to_string(i),
child);
++i;
}
} else if (v.is_string()) {
cfg.values_.insert_or_assign(prefix, v.as_string());
} else if (v.is_bool()) {
cfg.values_.insert_or_assign(prefix, v.as_bool() ? "true"
: "false");
} else if (v.is_number()) {
const double d = v.as_number();
if (d == static_cast<double>(static_cast<long long>(d))) {
cfg.values_.insert_or_assign(
prefix, std::to_string(static_cast<long long>(d)));
} else {
cfg.values_.insert_or_assign(prefix,
std::format("{}", d));
}
}
// null: key omitted
}
template <typename T> struct IsDuration : std::false_type {
};
template <typename Rep, typename Period>
struct IsDuration<std::chrono::duration<Rep, Period>>
: std::true_type {
};
template <typename T>
static Void::Result::Result<T, Void::Result::Error>
convert(std::string_view key, const std::string& raw)
{
auto fail = [&](std::string_view what) {
return Void::Result::fail(std::format(
"Configuration::Config::get_as: key '{}': {} ('{}')",
key, what, raw));
};
if constexpr (std::is_same_v<T, std::string>) {
return Void::Result::ok(raw);
} else if constexpr (std::is_same_v<T, bool>) {
std::string lower;
lower.reserve(raw.size());
for (const char c : raw) {
lower += static_cast<char>(
std::tolower(static_cast<unsigned char>(c)));
}
if (lower == "true" || lower == "1" || lower == "yes" ||
lower == "on") {
return Void::Result::ok(true);
}
if (lower == "false" || lower == "0" || lower == "no" ||
lower == "off") {
return Void::Result::ok(false);
}
return fail("not a boolean");
} else if constexpr (std::is_enum_v<T>) {
#ifdef VOID_HAS_ENUM_REFLECTION
if (auto e = Void::Detail::enum_parse<T>(raw);
e.has_value()) {
return Void::Result::ok(*e);
}
return fail("no such enumerator");
#else
return fail("enum parsing requires reflection");
#endif
} else if constexpr (IsDuration<T>::value) {
auto parsed = parse_duration(raw);
if (!parsed.has_value()) {
return fail("not a duration (use e.g. 250ms, 10s, 5m)");
}
return Void::Result::ok(
std::chrono::duration_cast<T>(*parsed));
} else if constexpr (std::is_arithmetic_v<T>) {
T value{};
const char* begin = raw.data();
const char* end = raw.data() + raw.size();
const auto [ptr, ec] = std::from_chars(begin, end, value);
if (ec == std::errc{} && ptr == end) {
return Void::Result::ok(value);
}
// Byte-size units for integral targets: "10MB", "1GiB".
if constexpr (std::is_integral_v<T>) {
if (auto bytes = parse_bytes(raw); bytes.has_value()) {
return Void::Result::ok(static_cast<T>(*bytes));
}
return fail("not a number or byte size");
}
return fail("not a number");
} else {
static_assert(std::is_same_v<T, std::string>,
"unsupported get_as<T> type");
}
}
static std::optional<std::chrono::nanoseconds>
parse_duration(const std::string& raw)
{
// Single source of truth lives in Time/Format.hpp.
return Void::Time::parse_duration(raw);
}
// Parse a byte-size string: a number followed by an SI
// (KB/MB/GB/TB, powers of 1000) or binary (KiB/MiB/GiB/TiB, powers
// of 1024) unit. A bare "B" or empty suffix means bytes. Returns
// nullopt otherwise.
static std::optional<std::uint64_t>
parse_bytes(const std::string& raw)
{
double number = 0;
const char* begin = raw.data();
const char* end = raw.data() + raw.size();
const auto [ptr, ec] = std::from_chars(begin, end, number);
if (ec != std::errc{} || ptr == begin) {
return std::nullopt;
}
std::string_view suffix{ptr, end};
while (!suffix.empty() && suffix.front() == ' ') {
suffix.remove_prefix(1);
}
double mult = 0;
if (suffix.empty() || suffix == "B") {
mult = 1.0;
} else if (suffix == "KB") {
mult = 1e3;
} else if (suffix == "MB") {
mult = 1e6;
} else if (suffix == "GB") {
mult = 1e9;
} else if (suffix == "TB") {
mult = 1e12;
} else if (suffix == "KiB") {
mult = 1024.0;
} else if (suffix == "MiB") {
mult = 1024.0 * 1024.0;
} else if (suffix == "GiB") {
mult = 1024.0 * 1024.0 * 1024.0;
} else if (suffix == "TiB") {
mult = 1024.0 * 1024.0 * 1024.0 * 1024.0;
} else {
return std::nullopt;
}
return static_cast<std::uint64_t>(number * mult);
}
std::unordered_map<std::string, std::string> values_;
};
} // namespace Void::Configuration