Files
Library/include/Void/Configuration/Schema.hpp
T

1031 lines
29 KiB
C++

#pragma once
#include <Void/Configuration/Bind.hpp>
#include <Void/Configuration/Config.hpp>
#include <Void/Core/Meta.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
namespace Void::Configuration
{
enum class ConfigErrorCode : std::int32_t {
none = 0,
invalid_argument = 1,
io_error = 2,
parse_error = 3,
limit_exceeded = 4,
key_collision = 5,
unknown_key = 6,
missing_required = 7,
type_mismatch = 8,
range_error = 9,
constraint_failed = 10,
vector_gap = 11,
restart_required = 12,
prepare_failed = 13,
cancelled = 14,
timeout = 15,
retention_limit = 16,
not_ready = 17,
internal = 18,
};
[[nodiscard]] inline Void::Result::Error
make_config_error(ConfigErrorCode code, std::string message = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case ConfigErrorCode::none:
kind = ErrorKind::internal;
break;
case ConfigErrorCode::invalid_argument:
case ConfigErrorCode::unknown_key:
case ConfigErrorCode::missing_required:
case ConfigErrorCode::type_mismatch:
case ConfigErrorCode::range_error:
case ConfigErrorCode::constraint_failed:
case ConfigErrorCode::vector_gap:
kind = ErrorKind::invalid_argument;
break;
case ConfigErrorCode::io_error:
kind = ErrorKind::io;
break;
case ConfigErrorCode::parse_error:
kind = ErrorKind::corrupt;
break;
case ConfigErrorCode::key_collision:
case ConfigErrorCode::restart_required:
kind = ErrorKind::conflict;
break;
case ConfigErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case ConfigErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case ConfigErrorCode::limit_exceeded:
case ConfigErrorCode::retention_limit:
kind = ErrorKind::exhausted;
break;
case ConfigErrorCode::prepare_failed:
case ConfigErrorCode::not_ready:
case ConfigErrorCode::internal:
kind = ErrorKind::internal;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kConfigurationErrorDomain,
static_cast<std::int32_t>(code)}};
}
struct ConfigLimits {
std::size_t max_source_bytes{1 * 1024 * 1024};
std::size_t max_sources{8};
std::size_t max_merged_bytes{4 * 1024 * 1024};
std::size_t max_keys{10'000};
std::size_t max_key_bytes{4 * 1024};
std::size_t max_scalar_bytes{64 * 1024};
std::size_t max_nesting_depth{32};
std::size_t max_vector_items{1024};
std::size_t max_diagnostics{100};
std::size_t max_participants{64};
std::size_t max_retained_generations{4};
std::size_t max_notifications{128};
std::chrono::milliseconds default_prepare_timeout{
std::chrono::seconds{5}};
};
enum class SourceKind : std::uint8_t {
Defaults = 0,
FileKeyValue = 1,
FileIni = 2,
FileJson = 3,
Environment = 4,
CliArgs = 5,
};
using SourceId = std::string;
struct SourceLocation {
SourceId source{};
std::string key{};
std::uint32_t line{0};
};
enum class ValueState : std::uint8_t {
Missing = 0,
Empty = 1,
Null = 2,
Present = 3,
Removed = 4,
};
struct SourceOrigin {
SourceId source{};
SourceKind kind{SourceKind::Defaults};
std::uint32_t line{0};
ValueState state{ValueState::Present};
};
struct KeyProvenance {
std::string key{};
SourceOrigin winner{};
std::vector<SourceOrigin> shadowed{};
bool redacted{false};
};
struct Provenance {
std::unordered_map<std::string, KeyProvenance> entries{};
[[nodiscard]] const KeyProvenance*
find(std::string_view key) const noexcept
{
const auto it = entries.find(std::string{key});
return it == entries.end() ? nullptr : &it->second;
}
};
struct SourceSpec {
SourceId id{};
SourceKind kind{SourceKind::Defaults};
std::filesystem::path file_path{};
std::string inline_text{};
std::vector<std::string> env_keys{};
std::string env_prefix{};
std::vector<std::pair<std::string, std::string>> entries{};
std::vector<std::string> cli_args{};
std::vector<std::string> removals{};
bool is_inline{false};
};
class SourceSet
{
public:
SourceSet& add_defaults_map(
SourceId id,
std::vector<std::pair<std::string, std::string>> kv)
{
SourceSpec spec;
spec.id = std::move(id);
spec.kind = SourceKind::Defaults;
spec.entries = std::move(kv);
m_specs.push_back(std::move(spec));
return *this;
}
SourceSet& add_json_file(SourceId id, std::filesystem::path path)
{
SourceSpec spec;
spec.id = std::move(id);
spec.kind = SourceKind::FileJson;
spec.file_path = std::move(path);
m_specs.push_back(std::move(spec));
return *this;
}
SourceSet& add_json_text(SourceId id, std::string text)
{
SourceSpec spec;
spec.id = std::move(id);
spec.kind = SourceKind::FileJson;
spec.inline_text = std::move(text);
spec.is_inline = true;
m_specs.push_back(std::move(spec));
return *this;
}
SourceSet& add_ini_file(SourceId id, std::filesystem::path path)
{
SourceSpec spec;
spec.id = std::move(id);
spec.kind = SourceKind::FileIni;
spec.file_path = std::move(path);
m_specs.push_back(std::move(spec));
return *this;
}
SourceSet& add_ini_text(SourceId id, std::string text)
{
SourceSpec spec;
spec.id = std::move(id);
spec.kind = SourceKind::FileIni;
spec.inline_text = std::move(text);
spec.is_inline = true;
m_specs.push_back(std::move(spec));
return *this;
}
SourceSet& add_kv_file(SourceId id, std::filesystem::path path)
{
SourceSpec spec;
spec.id = std::move(id);
spec.kind = SourceKind::FileKeyValue;
spec.file_path = std::move(path);
m_specs.push_back(std::move(spec));
return *this;
}
SourceSet& add_kv_text(SourceId id, std::string text)
{
SourceSpec spec;
spec.id = std::move(id);
spec.kind = SourceKind::FileKeyValue;
spec.inline_text = std::move(text);
spec.is_inline = true;
m_specs.push_back(std::move(spec));
return *this;
}
SourceSet& add_env_allowlist(SourceId id,
std::vector<std::string> keys)
{
SourceSpec spec;
spec.id = std::move(id);
spec.kind = SourceKind::Environment;
spec.env_keys = std::move(keys);
m_specs.push_back(std::move(spec));
return *this;
}
SourceSet& add_env_prefix(SourceId id, std::string prefix)
{
SourceSpec spec;
spec.id = std::move(id);
spec.kind = SourceKind::Environment;
spec.env_prefix = std::move(prefix);
m_specs.push_back(std::move(spec));
return *this;
}
SourceSet& add_env_map(
SourceId id,
std::vector<std::pair<std::string, std::string>> kv)
{
SourceSpec spec;
spec.id = std::move(id);
spec.kind = SourceKind::Environment;
spec.entries = std::move(kv);
m_specs.push_back(std::move(spec));
return *this;
}
SourceSet& add_cli_args(SourceId id, std::vector<std::string> args)
{
SourceSpec spec;
spec.id = std::move(id);
spec.kind = SourceKind::CliArgs;
spec.cli_args = std::move(args);
m_specs.push_back(std::move(spec));
return *this;
}
SourceSet& add_removals(SourceId id, SourceKind tier,
std::vector<std::string> keys)
{
SourceSpec spec;
spec.id = std::move(id);
spec.kind = tier;
spec.removals = std::move(keys);
m_specs.push_back(std::move(spec));
return *this;
}
[[nodiscard]] const std::vector<SourceSpec>& specs() const noexcept
{
return m_specs;
}
private:
std::vector<SourceSpec> m_specs{};
};
struct MergedEntry {
ValueState state{ValueState::Missing};
std::string value{};
SourceLocation location{};
};
struct MergedConfig {
std::map<std::string, MergedEntry> entries{};
std::shared_ptr<Provenance> provenance{
std::make_shared<Provenance>()};
std::uint64_t revision_digest{0};
[[nodiscard]] ValueState state_of(std::string_view key) const
{
const auto it = entries.find(std::string{key});
return it == entries.end() ? ValueState::Missing
: it->second.state;
}
[[nodiscard]] std::optional<std::string_view>
value_of(std::string_view key) const
{
const auto it = entries.find(std::string{key});
if (it == entries.end() ||
(it->second.state != ValueState::Present &&
it->second.state != ValueState::Empty)) {
return std::nullopt;
}
return std::string_view{it->second.value};
}
};
struct Diagnostic {
ConfigErrorCode code{ConfigErrorCode::none};
std::string category{};
SourceLocation location{};
std::string message{};
bool redacted{false};
};
[[nodiscard]] Void::Result::Result<MergedConfig> load_sources(
const SourceSet& sources, const ConfigLimits& limits = {},
const std::unordered_set<std::string>& secret_keys = {},
std::vector<Diagnostic>* diagnostics_out = nullptr);
// ── Typed Schema & Strict Binding ────────────────────────────────────
struct FieldRule {
std::string key{};
bool required{false};
bool secret{false};
bool restart_required{false};
bool is_vector{false};
bool is_optional{false};
std::optional<std::string> deprecated_message{};
std::optional<std::int64_t> int_min{};
std::optional<std::int64_t> int_max{};
std::optional<double> real_min{};
std::optional<double> real_max{};
};
template <typename T> struct Validated {
T value{};
std::shared_ptr<const Provenance> provenance{};
std::vector<std::string> warnings{};
std::vector<Diagnostic> diagnostics{};
};
namespace detail
{
[[nodiscard]] inline std::string
redact_display(std::string_view raw, bool is_secret)
{
return is_secret ? std::string{"[REDACTED]"} : std::string{raw};
}
[[nodiscard]] Void::Result::Result<bool>
parse_strict_bool(std::string_view raw);
[[nodiscard]] Void::Result::Result<std::int64_t>
parse_strict_i64_or_bytes(std::string_view raw, bool allow_bytes,
bool is_secret);
[[nodiscard]] Void::Result::Result<std::uint64_t>
parse_strict_u64_or_bytes(std::string_view raw, bool allow_bytes,
bool is_secret);
[[nodiscard]] Void::Result::Result<double>
parse_strict_real(std::string_view raw, bool is_secret);
[[nodiscard]] bool try_parse_vector_index(std::string_view suffix,
std::size_t& out);
} // namespace detail
template <typename T> class Schema
{
public:
struct Constraint {
std::string name{};
std::function<Void::Result::Result<void>(const T&)> check{};
};
explicit Schema(ConfigLimits limits = {}) : m_limits(limits) {}
#ifdef VOID_HAS_CONFIG_REFLECTION
[[nodiscard]] static Schema<T>
from_reflection(std::string_view prefix = {},
ConfigLimits limits = {})
{
Schema<T> s{limits};
collect_reflection<T>(s, prefix);
return s;
}
#endif
Schema& allow_unknown_keys(bool allow)
{
m_allow_unknown = allow;
return *this;
}
[[nodiscard]] bool allows_unknown_keys() const noexcept
{
return m_allow_unknown;
}
[[nodiscard]] const ConfigLimits& limits() const noexcept
{
return m_limits;
}
Schema& field(FieldRule rule)
{
m_rules[rule.key] = std::move(rule);
return *this;
}
Schema& secret(std::string_view key, bool v = true)
{
m_rules[std::string{key}].key = std::string{key};
m_rules[std::string{key}].secret = v;
return *this;
}
Schema& restart_required(std::string_view key, bool v = true)
{
m_rules[std::string{key}].key = std::string{key};
m_rules[std::string{key}].restart_required = v;
return *this;
}
Schema& deprecate(std::string_view key, std::string msg)
{
m_rules[std::string{key}].key = std::string{key};
m_rules[std::string{key}].deprecated_message = std::move(msg);
return *this;
}
Schema& int_range(std::string_view key, std::int64_t lo,
std::int64_t hi)
{
auto& r = m_rules[std::string{key}];
r.key = std::string{key};
r.int_min = lo;
r.int_max = hi;
return *this;
}
Schema& real_range(std::string_view key, double lo, double hi)
{
auto& r = m_rules[std::string{key}];
r.key = std::string{key};
r.real_min = lo;
r.real_max = hi;
return *this;
}
Schema& add_constraint(
std::string name,
std::function<Void::Result::Result<void>(const T&)> fn)
{
m_constraints.push_back(
Constraint{std::move(name), std::move(fn)});
return *this;
}
[[nodiscard]] const std::map<std::string, FieldRule>&
rules() const noexcept
{
return m_rules;
}
[[nodiscard]] const std::vector<Constraint>&
constraints() const noexcept
{
return m_constraints;
}
[[nodiscard]] std::unordered_set<std::string> secret_keys() const
{
std::unordered_set<std::string> out;
for (const auto& [k, r] : m_rules) {
if (r.secret) {
out.insert(k);
}
}
return out;
}
[[nodiscard]] const FieldRule* find_rule(std::string_view key) const
{
const auto it = m_rules.find(std::string{key});
return it == m_rules.end() ? nullptr : &it->second;
}
private:
#ifdef VOID_HAS_CONFIG_REFLECTION
template <typename Agg>
static void collect_reflection(Schema<T>& s,
std::string_view prefix)
{
template for (constexpr auto m : Void::Meta::members_v<Agg>)
{
using MT = [:std::meta::type_of(m):];
constexpr auto ko = Void::Meta::annotation_of<Key>(m);
const std::string seg =
ko.has_value()
? std::string{ko->name.view()}
: std::string{std::meta::identifier_of(m)};
const std::string full =
prefix.empty() ? seg
: std::string{prefix} + "." + seg;
if constexpr (BindDetail::BindableAggregate<MT> &&
!BindDetail::Leaf<MT>) {
collect_reflection<MT>(s, full);
} else {
FieldRule r;
r.key = full;
r.required = Void::Meta::has_annotation<Required>(m);
r.secret = Void::Meta::has_annotation<Secret>(m);
r.restart_required =
Void::Meta::has_annotation<RestartRequired>(m);
r.is_vector = Void::Meta::is_vector_v<MT>;
r.is_optional = Void::Meta::is_optional_v<MT>;
if constexpr (constexpr auto dep =
Void::Meta::annotation_of<Deprecated>(
m);
dep.has_value()) {
r.deprecated_message = std::string{dep->message.view()};
}
if constexpr (constexpr auto ir =
Void::Meta::annotation_of<IntRange>(m);
ir.has_value()) {
r.int_min = ir->min;
r.int_max = ir->max;
}
if constexpr (constexpr auto rr =
Void::Meta::annotation_of<RealRange>(
m);
rr.has_value()) {
r.real_min = rr->min;
r.real_max = rr->max;
}
s.m_rules.emplace(full, std::move(r));
}
}
}
#endif
ConfigLimits m_limits{};
bool m_allow_unknown{false};
std::map<std::string, FieldRule> m_rules{};
std::vector<Constraint> m_constraints{};
};
namespace SchemaDetail
{
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 LeafT>
Void::Result::Result<LeafT> convert_strict(std::string_view key,
const MergedEntry& entry,
const FieldRule* rule)
{
const bool is_secret = rule != nullptr && rule->secret;
auto fail_cat = [&](ConfigErrorCode code, std::string_view msg) {
return Void::Result::fail(make_config_error(
code,
std::format(
"Configuration: key '{}' (source={}, line={}): {} ('{}')",
key, entry.location.source, entry.location.line, msg,
detail::redact_display(entry.value, is_secret))));
};
if (entry.state == ValueState::Null) {
return fail_cat(ConfigErrorCode::type_mismatch,
"null cannot bind to non-optional field");
}
if constexpr (std::is_same_v<LeafT, std::string>) {
return entry.value;
} else {
if (entry.state == ValueState::Empty || entry.value.empty()) {
return fail_cat(ConfigErrorCode::type_mismatch,
"empty value is invalid for typed field");
}
if constexpr (std::is_same_v<LeafT, bool>) {
auto r = detail::parse_strict_bool(entry.value);
if (!r) {
return fail_cat(ConfigErrorCode::type_mismatch,
r.error().message());
}
return *r;
} else if constexpr (std::is_enum_v<LeafT>) {
#ifdef VOID_HAS_ENUM_REFLECTION
if (auto e = Void::Detail::enum_parse<LeafT>(entry.value);
e.has_value()) {
return *e;
}
return fail_cat(ConfigErrorCode::type_mismatch,
"unknown enum value");
#else
return fail_cat(ConfigErrorCode::type_mismatch,
"enum reflection disabled");
#endif
} else if constexpr (IsDuration<LeafT>::value) {
auto parsed = Void::Time::parse_duration(entry.value);
if (!parsed.has_value()) {
return fail_cat(ConfigErrorCode::type_mismatch,
"invalid duration");
}
return std::chrono::duration_cast<LeafT>(*parsed);
} else if constexpr (std::is_floating_point_v<LeafT>) {
auto r = detail::parse_strict_real(entry.value, is_secret);
if (!r) {
return fail_cat(ConfigErrorCode::type_mismatch,
r.error().message());
}
if (rule != nullptr) {
if (rule->real_min.has_value() && *r < *rule->real_min) {
return fail_cat(ConfigErrorCode::range_error,
"below minimum");
}
if (rule->real_max.has_value() && *r > *rule->real_max) {
return fail_cat(ConfigErrorCode::range_error,
"above maximum");
}
}
return static_cast<LeafT>(*r);
} else if constexpr (std::is_integral_v<LeafT> &&
std::is_signed_v<LeafT>) {
auto r = detail::parse_strict_i64_or_bytes(
entry.value, true, is_secret);
if (!r) {
return fail_cat(ConfigErrorCode::type_mismatch,
r.error().message());
}
if (*r < static_cast<std::int64_t>(
std::numeric_limits<LeafT>::min()) ||
*r > static_cast<std::int64_t>(
std::numeric_limits<LeafT>::max())) {
return fail_cat(ConfigErrorCode::range_error,
"integer out of target type range");
}
if (rule != nullptr) {
if (rule->int_min.has_value() && *r < *rule->int_min) {
return fail_cat(ConfigErrorCode::range_error,
"below minimum");
}
if (rule->int_max.has_value() && *r > *rule->int_max) {
return fail_cat(ConfigErrorCode::range_error,
"above maximum");
}
}
return static_cast<LeafT>(*r);
} else if constexpr (std::is_integral_v<LeafT> &&
std::is_unsigned_v<LeafT>) {
auto r = detail::parse_strict_u64_or_bytes(
entry.value, true, is_secret);
if (!r) {
return fail_cat(ConfigErrorCode::type_mismatch,
r.error().message());
}
if (*r > static_cast<std::uint64_t>(
std::numeric_limits<LeafT>::max())) {
return fail_cat(ConfigErrorCode::range_error,
"unsigned integer out of target range");
}
if (rule != nullptr) {
if (rule->int_min.has_value() &&
*r < static_cast<std::uint64_t>(
std::max<std::int64_t>(0, *rule->int_min))) {
return fail_cat(ConfigErrorCode::range_error,
"below minimum");
}
if (rule->int_max.has_value() &&
(*rule->int_max < 0 ||
*r > static_cast<std::uint64_t>(*rule->int_max))) {
return fail_cat(ConfigErrorCode::range_error,
"above maximum");
}
}
return static_cast<LeafT>(*r);
} else {
static_assert(std::is_same_v<LeafT, std::string>,
"unsupported strict config field type");
}
}
}
#ifdef VOID_HAS_CONFIG_REFLECTION
template <typename RootT, typename Agg>
void bind_strict_into(const MergedConfig& cfg,
const Schema<RootT>& schema,
std::string_view prefix, Agg& out,
std::vector<Diagnostic>& diags,
std::vector<std::string>& warnings,
std::unordered_set<std::string>& consumed_keys)
{
auto push_diag = [&](ConfigErrorCode code, std::string cat,
const SourceLocation& loc, std::string msg,
bool redacted) {
if (diags.size() < schema.limits().max_diagnostics) {
diags.push_back(Diagnostic{code, std::move(cat), loc,
std::move(msg), redacted});
}
};
template for (constexpr auto m : Void::Meta::members_v<Agg>)
{
using MT = [:std::meta::type_of(m):];
constexpr auto ko = Void::Meta::annotation_of<Key>(m);
const std::string seg =
ko.has_value() ? std::string{ko->name.view()}
: std::string{std::meta::identifier_of(m)};
const std::string full =
prefix.empty() ? seg : std::string{prefix} + "." + seg;
const FieldRule* rule = schema.find_rule(full);
const bool is_secret =
(rule != nullptr && rule->secret) ||
Void::Meta::has_annotation<Secret>(m);
const bool is_required =
(rule != nullptr && rule->required) ||
Void::Meta::has_annotation<Required>(m);
if constexpr (BindDetail::BindableAggregate<MT> &&
!BindDetail::Leaf<MT>) {
bind_strict_into<RootT, MT>(cfg, schema, full, out.[:m:],
diags, warnings, consumed_keys);
} else if constexpr (Void::Meta::is_optional_v<MT>) {
using U = typename MT::value_type;
const auto it = cfg.entries.find(full);
if (it != cfg.entries.end()) {
consumed_keys.insert(full);
if (rule != nullptr &&
rule->deprecated_message.has_value()) {
warnings.push_back(full + ": " +
*rule->deprecated_message);
}
if (it->second.state == ValueState::Null) {
out.[:m:].reset();
} else if (it->second.state != ValueState::Missing &&
it->second.state != ValueState::Removed) {
auto v = convert_strict<U>(full, it->second, rule);
if (!v) {
push_diag(static_cast<ConfigErrorCode>(
v.error().code().value),
"conversion", it->second.location,
v.error().message(), is_secret);
} else {
out.[:m:] = std::move(*v);
}
}
}
} else if constexpr (Void::Meta::is_vector_v<MT>) {
using U = typename MT::value_type;
const std::string item_prefix = full + ".";
std::map<std::size_t, const MergedEntry*> indexed;
std::size_t max_idx = 0;
bool any = false;
bool had_bad_suffix = false;
for (auto it = cfg.entries.lower_bound(item_prefix);
it != cfg.entries.end() &&
it->first.starts_with(item_prefix);
++it) {
const std::string_view suffix =
std::string_view{it->first}.substr(
item_prefix.size());
if (suffix.find('.') != std::string_view::npos) {
continue;
}
consumed_keys.insert(it->first);
if (it->second.state == ValueState::Missing ||
it->second.state == ValueState::Removed) {
continue;
}
std::size_t idx = 0;
if (!detail::try_parse_vector_index(suffix, idx)) {
had_bad_suffix = true;
push_diag(ConfigErrorCode::vector_gap, "vector",
it->second.location,
"non-numeric vector index key '" +
it->first + "'",
is_secret);
continue;
}
if (idx >= schema.limits().max_vector_items) {
push_diag(ConfigErrorCode::limit_exceeded, "limit",
it->second.location,
"vector index exceeds max_vector_items",
is_secret);
continue;
}
indexed[idx] = &it->second;
if (!any || idx > max_idx) max_idx = idx;
any = true;
}
if (any && !had_bad_suffix) {
MT items;
for (std::size_t i = 0; i <= max_idx; ++i) {
const auto idx_it = indexed.find(i);
if (idx_it == indexed.end()) {
push_diag(
ConfigErrorCode::vector_gap, "vector",
SourceLocation{.source = "",
.key = item_prefix +
std::to_string(i)},
"gap in vector indices at '" + item_prefix +
std::to_string(i) + "'",
false);
continue;
}
auto v = convert_strict<U>(
item_prefix + std::to_string(i),
*idx_it->second, rule);
if (!v) {
push_diag(static_cast<ConfigErrorCode>(
v.error().code().value),
"conversion",
idx_it->second->location,
v.error().message(), is_secret);
} else {
items.push_back(std::move(*v));
}
}
if (diags.empty()) {
out.[:m:] = std::move(items);
}
}
} else {
const auto it = cfg.entries.find(full);
if (it != cfg.entries.end()) {
consumed_keys.insert(full);
if (it->second.state == ValueState::Missing ||
it->second.state == ValueState::Removed) {
if (is_required) {
push_diag(ConfigErrorCode::missing_required,
"required", it->second.location,
"missing required key '" + full + "'",
is_secret);
}
} else {
if (rule != nullptr &&
rule->deprecated_message.has_value()) {
warnings.push_back(full + ": " +
*rule->deprecated_message);
}
auto v = convert_strict<MT>(full, it->second, rule);
if (!v) {
push_diag(static_cast<ConfigErrorCode>(
v.error().code().value),
"conversion", it->second.location,
v.error().message(), is_secret);
} else {
out.[:m:] = std::move(*v);
}
}
} else if (is_required) {
push_diag(
ConfigErrorCode::missing_required, "required",
SourceLocation{.source = "", .key = full},
"missing required key '" + full + "'", is_secret);
}
}
}
}
#endif
} // namespace SchemaDetail
template <typename T>
[[nodiscard]] Void::Result::Result<Validated<T>>
validate(const MergedConfig& cfg, const Schema<T>& schema)
{
Validated<T> result;
result.provenance = cfg.provenance;
std::vector<Diagnostic>& diags = result.diagnostics;
std::unordered_set<std::string> consumed_keys;
#ifdef VOID_HAS_CONFIG_REFLECTION
if constexpr (BindDetail::BindableAggregate<T>) {
SchemaDetail::bind_strict_into<T, T>(
cfg, schema, {}, result.value, diags, result.warnings,
consumed_keys);
}
#endif
if (!schema.allows_unknown_keys()) {
for (const auto& [k, entry] : cfg.entries) {
if (entry.state == ValueState::Missing ||
entry.state == ValueState::Removed) {
continue;
}
if (!consumed_keys.contains(k) &&
diags.size() < schema.limits().max_diagnostics) {
diags.push_back(Diagnostic{
ConfigErrorCode::unknown_key,
"unknown_key",
entry.location,
"unknown configuration key '" + k + "'",
false,
});
}
}
}
if (diags.empty()) {
for (const auto& c : schema.constraints()) {
auto cr = c.check(result.value);
if (!cr && diags.size() < schema.limits().max_diagnostics) {
diags.push_back(Diagnostic{
ConfigErrorCode::constraint_failed,
"constraint:" + c.name,
SourceLocation{},
cr.error().message(),
false,
});
}
}
}
if (!diags.empty()) {
const auto primary = diags.front();
std::string summary = primary.message;
if (diags.size() > 1) {
summary += std::format(" (+{} more diagnostic(s))",
diags.size() - 1);
}
return Void::Result::fail(make_config_error(primary.code, summary));
}
return result;
}
template <typename T>
[[nodiscard]] Void::Result::Result<Validated<T>>
validate(const Config& cfg, const Schema<T>& schema)
{
SourceSet ss;
std::vector<std::pair<std::string, std::string>> kvs;
for (const auto& k : cfg.keys()) {
kvs.emplace_back(k, std::string{cfg.get_or(k)});
}
ss.add_defaults_map("config", std::move(kvs));
auto merged = load_sources(ss, schema.limits(), schema.secret_keys());
if (!merged) {
return Void::Result::fail(std::move(merged).error());
}
return validate<T>(*merged, schema);
}
template <typename T>
[[nodiscard]] std::vector<std::string> detect_restart_required_changes(
const MergedConfig& old_cfg, const MergedConfig& new_cfg,
const Schema<T>& schema)
{
std::vector<std::string> changed;
for (const auto& [k, rule] : schema.rules()) {
if (!rule.restart_required) {
continue;
}
const auto old_it = old_cfg.entries.find(k);
const auto new_it = new_cfg.entries.find(k);
const ValueState old_s =
old_it == old_cfg.entries.end() ? ValueState::Missing
: old_it->second.state;
const ValueState new_s =
new_it == new_cfg.entries.end() ? ValueState::Missing
: new_it->second.state;
if (old_s != new_s ||
(old_it != old_cfg.entries.end() &&
new_it != new_cfg.entries.end() &&
old_it->second.value != new_it->second.value)) {
changed.push_back(k);
}
}
return changed;
}
} // namespace Void::Configuration