diff --git a/include/Void/Configuration/Bind.hpp b/include/Void/Configuration/Bind.hpp index fcff8c6..2f7c568 100644 --- a/include/Void/Configuration/Bind.hpp +++ b/include/Void/Configuration/Bind.hpp @@ -51,6 +51,21 @@ namespace Void::Configuration }; struct Required { }; + struct Secret { + }; + struct RestartRequired { + }; + struct Deprecated { + Void::Meta::Str message; + }; + struct IntRange { + std::int64_t min{0}; + std::int64_t max{0}; + }; + struct RealRange { + double min{0.0}; + double max{0.0}; + }; #ifdef VOID_HAS_CONFIG_REFLECTION diff --git a/include/Void/Configuration/ReloadController.hpp b/include/Void/Configuration/ReloadController.hpp new file mode 100644 index 0000000..3953ce0 --- /dev/null +++ b/include/Void/Configuration/ReloadController.hpp @@ -0,0 +1,784 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Configuration +{ + struct PreparedChange { + std::shared_ptr view{}; + std::size_t declared_budget_bytes{0}; + std::function>()> + dispose_async{}; + }; + + template struct Snapshot { + std::uint64_t generation{0}; + std::shared_ptr values{}; + std::shared_ptr provenance{}; + std::shared_ptr raw{}; + std::shared_ptr< + const std::unordered_map>> + resources{}; + std::shared_ptr retention_token{}; + + template + [[nodiscard]] std::shared_ptr + resource(std::string_view participant_id) const + { + if (!resources) { + return nullptr; + } + const auto it = resources->find(std::string{participant_id}); + if (it == resources->end()) { + return nullptr; + } + return std::static_pointer_cast(it->second); + } + + [[nodiscard]] explicit operator bool() const noexcept + { + return values != nullptr; + } + }; + + template struct PreparedAggregate { + std::shared_ptr values{}; + std::shared_ptr provenance{}; + std::shared_ptr raw{}; + std::shared_ptr< + const std::unordered_map>> + resources{}; + std::vector staged_changes{}; + std::vector changed_keys{}; + std::vector warnings{}; + + Void::Coro::Task> dispose_all() + { + for (auto it = staged_changes.rbegin(); + it != staged_changes.rend(); ++it) { + if (it->dispose_async) { + (void)co_await it->dispose_async(); + } + } + staged_changes.clear(); + co_return Void::Result::Result{}; + } + }; + + struct ReloadReport { + std::uint64_t generation{0}; + bool committed{false}; + bool restart_required{false}; + std::vector restart_required_keys{}; + bool stop_observed_after_commit{false}; + std::vector changed_keys{}; + std::vector notification_errors{}; + std::vector warnings{}; + std::size_t coalesced_events{0}; + }; + + namespace detail + { + class AsyncReloadGate + { + public: + + struct Waiter { + Void::Async::Executor* exec{nullptr}; + std::coroutine_handle<> h{}; + }; + + struct Guard { + AsyncReloadGate* gate{nullptr}; + Guard() noexcept = default; + explicit Guard(AsyncReloadGate* g) noexcept : gate(g) {} + Guard(Guard&& o) noexcept + : gate(std::exchange(o.gate, nullptr)) + { + } + Guard& operator=(Guard&& o) noexcept + { + if (this != &o) { + if (gate != nullptr) gate->release(); + gate = std::exchange(o.gate, nullptr); + } + return *this; + } + ~Guard() + { + if (gate != nullptr) { + gate->release(); + } + } + Guard(const Guard&) = delete; + Guard& operator=(const Guard&) = delete; + }; + + struct Awaiter { + AsyncReloadGate* gate; + Void::Async::Executor* exec; + bool await_ready() noexcept { return gate->try_lock(); } + bool await_suspend(std::coroutine_handle<> h) noexcept + { + return gate->enqueue_or_acquire(exec, h); + } + Guard await_resume() noexcept { return Guard{gate}; } + }; + + Awaiter lock(Void::Async::Executor* exec) noexcept + { + return Awaiter{this, exec}; + } + + bool try_lock() noexcept; + bool enqueue_or_acquire(Void::Async::Executor* exec, + std::coroutine_handle<> h) noexcept; + void release() noexcept; + + private: + + std::mutex mu_{}; + bool locked_{false}; + std::deque waiters_{}; + }; + + [[nodiscard]] std::vector + diff_merged_keys(const MergedConfig& old_cfg, + const MergedConfig& new_cfg); + } // namespace detail + + struct ControllerOptions { + const Void::Time::MonotonicClock* clock{ + &Void::Time::SystemMonotonicClock::instance()}; + Void::Async::Executor* executor{nullptr}; + }; + + template + class ReloadController + : public std::enable_shared_from_this> + { + public: + + using PrepareFn = std::function< + Void::Coro::Task>( + const Snapshot& old_snapshot, + const std::shared_ptr& candidate, + Void::Async::OperationOptions options)>; + + using CommitListener = + std::function& snapshot, + const ReloadReport& report)>; + + [[nodiscard]] static Void::Result::Result< + std::shared_ptr>> + create(Schema schema, SourceSet initial_sources, + ControllerOptions options = {}) + { + auto merged = load_sources(initial_sources, schema.limits(), + schema.secret_keys()); + if (!merged) { + return Void::Result::fail(std::move(merged).error()); + } + auto validated = validate(*merged, schema); + if (!validated) { + return Void::Result::fail(std::move(validated).error()); + } + + auto ctrl = std::shared_ptr>( + new ReloadController(std::move(schema), options)); + auto merged_ptr = + std::make_shared(std::move(*merged)); + auto val_ptr = + std::make_shared(std::move(validated->value)); + auto res_ptr = std::make_shared>>(); + auto tok = std::make_shared(1); + ctrl->m_retention_tokens.push_back(tok); + ctrl->m_current = Snapshot{ + .generation = 1, + .values = std::move(val_ptr), + .provenance = merged_ptr->provenance, + .raw = std::move(merged_ptr), + .resources = std::move(res_ptr), + .retention_token = std::move(tok), + }; + ctrl->m_generation = 1; + return ctrl; + } + + ~ReloadController() { close_and_join(); } + + ReloadController(const ReloadController&) = delete; + ReloadController& operator=(const ReloadController&) = delete; + + [[nodiscard]] Snapshot current() const + { + std::lock_guard lk{m_pub_mu}; + return m_current; + } + + [[nodiscard]] std::size_t retained_generation_count() const + { + std::lock_guard lk{m_pub_mu}; + std::size_t live = 0; + for (const auto& w : m_retention_tokens) { + if (!w.expired()) ++live; + } + return live; + } + + Void::Result::Result + register_participant(std::string id, + std::size_t declared_budget_bytes, + PrepareFn prepare_fn) + { + if (id.empty() || !prepare_fn) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::invalid_argument, + "ReloadController: participant id and callback required")); + } + std::lock_guard lk{m_part_mu}; + if (m_closing) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::prepare_failed, + "ReloadController: controller closing")); + } + if (m_participants.size() >= m_schema.limits().max_participants) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "ReloadController: max_participants exceeded")); + } + for (const auto& p : m_participants) { + if (p.id == id && !p.removing) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::key_collision, + "ReloadController: duplicate participant id '" + + id + "'")); + } + } + m_participants.push_back(ParticipantEntry{ + .id = std::move(id), + .budget_bytes = declared_budget_bytes, + .prepare = std::move(prepare_fn), + .in_flight = 0, + .removing = false, + }); + return {}; + } + + void unregister_participant(std::string_view id) + { + std::unique_lock lk{m_part_mu}; + for (auto& p : m_participants) { + if (p.id == id) { + p.removing = true; + break; + } + } + m_part_cv.wait(lk, [&] { + for (const auto& p : m_participants) { + if (p.id == id && p.in_flight > 0) return false; + } + return true; + }); + std::erase_if(m_participants, [&](const ParticipantEntry& p) { + return p.id == id; + }); + } + + std::size_t on_committed(CommitListener listener) + { + std::lock_guard lk{m_listener_mu}; + const std::size_t id = m_next_listener_id++; + m_listeners.emplace_back(id, std::move(listener)); + return id; + } + + void remove_listener(std::size_t id) + { + std::lock_guard lk{m_listener_mu}; + std::erase_if(m_listeners, [id](const auto& pair) { + return pair.first == id; + }); + } + + /// Prepare-only port exporting a staged candidate aggregate for a + /// higher-level platform coordinator without swapping m_current. + [[nodiscard]] Void::Coro::Task< + Void::Result::Result>> + prepare_external(SourceSet sources, + Void::Async::OperationOptions opts = {}) + { + auto gate_guard = co_await m_gate.lock(m_executor); + if (opts.stop.stop_requested()) { + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::cancelled, + "ReloadController::prepare_external: cancelled")); + } + auto snap = current(); + co_return co_await prepare_candidate( + std::move(sources), snap, opts, nullptr); + } + + [[nodiscard]] Void::Coro::Task> + reload(SourceSet sources, Void::Async::OperationOptions opts = {}) + { + if (opts.stop.stop_requested()) { + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::cancelled, + "ReloadController::reload: cancelled before admission")); + } + + auto gate_guard = co_await m_gate.lock(m_executor); + if (opts.stop.stop_requested()) { + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::cancelled, + "ReloadController::reload: cancelled while queued")); + } + + Snapshot old_snap; + std::uint64_t expected_gen = 0; + { + std::lock_guard lk{m_pub_mu}; + std::erase_if(m_retention_tokens, [](const auto& w) { + return w.expired(); + }); + if (m_schema.limits().max_retained_generations > 0 && + m_retention_tokens.size() >= + m_schema.limits().max_retained_generations) { + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::retention_limit, + "ReloadController::reload: max_retained_generations reached")); + } + old_snap = m_current; + expected_gen = m_generation; + } + + std::vector restart_keys; + auto cand_res = co_await prepare_candidate( + std::move(sources), old_snap, opts, &restart_keys); + if (!restart_keys.empty()) { + ReloadReport rep; + rep.generation = expected_gen; + rep.committed = false; + rep.restart_required = true; + rep.restart_required_keys = std::move(restart_keys); + co_return rep; + } + if (!cand_res) { + co_return Void::Result::fail(std::move(cand_res).error()); + } + auto agg = std::move(*cand_res); + + // Check pre-commit stop/deadline before swapping m_current. + if (opts.stop.stop_requested()) { + (void)co_await agg.dispose_all(); + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::cancelled, + "ReloadController::reload: cancelled before commit")); + } + if (opts.deadline.has_value() && + m_clock->now() >= *opts.deadline) { + (void)co_await agg.dispose_all(); + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::timeout, + "ReloadController::reload: deadline expired before commit")); + } + + // Short pointer swap — commit point (zero user callbacks or + // allocations under m_pub_mu). + auto tok = std::make_shared(1); + Snapshot new_snap{ + .generation = expected_gen + 1, + .values = std::move(agg.values), + .provenance = std::move(agg.provenance), + .raw = std::move(agg.raw), + .resources = std::move(agg.resources), + .retention_token = tok, + }; + Snapshot retired_old; + { + std::lock_guard lk{m_pub_mu}; + if (m_generation != expected_gen || m_closing) { + // Should be impossible under m_gate, fail-safe rollback. + retired_old = Snapshot{}; + } else { + m_generation = new_snap.generation; + m_retention_tokens.push_back(tok); + retired_old = std::exchange(m_current, new_snap); + } + } + if (!retired_old) { + (void)co_await agg.dispose_all(); + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::internal, + "ReloadController::reload: generation swap conflict")); + } + + // Release old snapshot outside lock. + retired_old = Snapshot{}; + + ReloadReport rep; + rep.generation = new_snap.generation; + rep.committed = true; + rep.changed_keys = std::move(agg.changed_keys); + rep.warnings = std::move(agg.warnings); + rep.stop_observed_after_commit = opts.stop.stop_requested(); + rep.coalesced_events = + m_coalesced_events.exchange(0, std::memory_order_acq_rel); + + // Notify observers strictly outside locks; capture exceptions + // without claiming rollback. + std::vector copy; + { + std::lock_guard lk{m_listener_mu}; + copy.reserve(m_listeners.size()); + for (const auto& [_, fn] : m_listeners) { + if (fn) copy.push_back(fn); + } + } + const std::size_t notify_cap = + std::min(copy.size(), m_schema.limits().max_notifications); + for (std::size_t i = 0; i < notify_cap; ++i) { + try { + copy[i](new_snap, rep); + } catch (const std::exception& ex) { + rep.notification_errors.push_back(make_config_error( + ConfigErrorCode::internal, ex.what())); + } catch (...) { + rep.notification_errors.push_back(make_config_error( + ConfigErrorCode::internal, + "ReloadController: notification callback threw")); + } + } + co_return rep; + } + + [[nodiscard]] Void::Result::Result attach_watcher( + Void::SystemAsync::WatcherService& watcher, + std::vector paths, + std::function build_sources, + Void::Async::Executor& exec) + { + std::lock_guard lk{m_watch_mu}; + if (m_closing) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::internal, + "ReloadController::attach_watcher: controller closing")); + } + std::weak_ptr> weak_self = + this->weak_from_this(); + auto on_change = [weak_self, build = std::move(build_sources), + &exec](const Void::SystemAsync::WatchEvent&) { + auto self = weak_self.lock(); + if (!self) return; + if (self->m_watcher_busy.exchange( + true, std::memory_order_acq_rel)) { + self->m_coalesced_events.fetch_add( + 1, std::memory_order_relaxed); + self->m_watcher_dirty.store(true, + std::memory_order_release); + return; + } + self->schedule_watch_reload(build, exec); + }; + + std::vector subs; + for (const auto& p : paths) { + auto sr = watcher.watch(p, on_change); + if (!sr) { + for (auto& s : subs) (void)s.close_and_join(); + return Void::Result::fail(std::move(sr).error()); + } + subs.push_back(std::move(*sr)); + } + for (auto& s : subs) { + m_watch_subs.push_back(std::move(s)); + } + return {}; + } + + void close_and_join() + { + { + std::lock_guard lk{m_part_mu}; + m_closing = true; + } + { + std::lock_guard lk{m_pub_mu}; + m_closing = true; + } + std::vector subs; + { + std::lock_guard lk{m_watch_mu}; + subs.swap(m_watch_subs); + } + for (auto& s : subs) { + (void)s.close_and_join(); + } + std::unique_lock lk{m_part_mu}; + m_part_cv.wait(lk, [&] { + for (const auto& p : m_participants) { + if (p.in_flight > 0) return false; + } + return true; + }); + } + + private: + + struct ParticipantEntry { + std::string id{}; + std::size_t budget_bytes{0}; + PrepareFn prepare{}; + std::size_t in_flight{0}; + bool removing{false}; + }; + + ReloadController(Schema schema, ControllerOptions opts) + : m_schema(std::move(schema)), + m_clock(opts.clock ? opts.clock + : &Void::Time::SystemMonotonicClock::instance()), + m_executor(opts.executor) + { + } + + static Void::Coro::Task run_watch_reload_task( + std::weak_ptr> weak_self, + std::function build, + Void::Async::Executor* exec) + { + for (;;) { + auto self = weak_self.lock(); + if (!self) co_return; + self->m_watcher_dirty.store(false, + std::memory_order_release); + auto res = co_await self->reload(build()); + (void)res; + if (!self->m_watcher_dirty.load( + std::memory_order_acquire)) { + self->m_watcher_busy.store(false, + std::memory_order_release); + if (!self->m_watcher_dirty.load( + std::memory_order_acquire)) { + co_return; + } + if (self->m_watcher_busy.exchange( + true, std::memory_order_acq_rel)) { + co_return; + } + } + } + (void)exec; + } + + void schedule_watch_reload(const std::function& build, + Void::Async::Executor& exec) + { + Void::Async::spawn( + exec, run_watch_reload_task(this->weak_from_this(), build, + &exec)); + } + + Void::Coro::Task>> + prepare_candidate(SourceSet sources, + const Snapshot& old_snap, + Void::Async::OperationOptions opts, + std::vector* restart_out) + { + auto merged = load_sources(sources, m_schema.limits(), + m_schema.secret_keys()); + if (!merged) { + co_return Void::Result::fail(std::move(merged).error()); + } + auto validated = validate(*merged, m_schema); + if (!validated) { + co_return Void::Result::fail(std::move(validated).error()); + } + if (restart_out != nullptr && old_snap.raw) { + auto rr = detect_restart_required_changes( + *old_snap.raw, *merged, m_schema); + if (!rr.empty()) { + *restart_out = std::move(rr); + co_return Void::Result::fail(make_config_error( + ConfigErrorCode::restart_required, + "ReloadController: restart-required keys changed")); + } + } + + auto merged_ptr = + std::make_shared(std::move(*merged)); + auto cand_ptr = + std::make_shared(std::move(validated->value)); + auto res_map = std::make_shared< + std::unordered_map>>(); + std::vector prepared_list; + + const auto prep_deadline = + m_clock->now() + m_schema.limits().default_prepare_timeout; + Void::Async::OperationOptions p_opts = opts; + if (!p_opts.deadline.has_value() || + prep_deadline < *p_opts.deadline) { + p_opts.deadline = prep_deadline; + } + + // Snapshot participants safely. + struct ActivePart { + std::string id; + std::size_t budget_bytes; + PrepareFn prepare; + }; + std::vector parts; + { + std::lock_guard lk{m_part_mu}; + for (auto& p : m_participants) { + if (!p.removing && p.prepare) { + ++p.in_flight; + parts.push_back( + ActivePart{p.id, p.budget_bytes, p.prepare}); + } + } + } + auto release_inflight = [&]() { + std::lock_guard lk{m_part_mu}; + for (auto& ap : parts) { + for (auto& p : m_participants) { + if (p.id == ap.id && p.in_flight > 0) { + --p.in_flight; + } + } + } + m_part_cv.notify_all(); + }; + + std::optional prep_err; + std::size_t total_budget = 0; + + for (auto& ap : parts) { + if (p_opts.stop.stop_requested()) { + prep_err = make_config_error( + ConfigErrorCode::cancelled, + "ReloadController: cancelled during participant prepare"); + break; + } + if (p_opts.deadline.has_value() && + m_clock->now() >= *p_opts.deadline) { + prep_err = make_config_error( + ConfigErrorCode::timeout, + "ReloadController: participant prepare timed out"); + break; + } + try { + auto pr = + co_await ap.prepare(old_snap, cand_ptr, p_opts); + if (!pr) { + prep_err = std::move(pr).error(); + break; + } + const std::size_t item_budget = std::max( + ap.budget_bytes, pr->declared_budget_bytes); + if (total_budget + item_budget > + m_schema.limits().max_merged_bytes) { + if (pr->dispose_async) { + (void)co_await pr->dispose_async(); + } + prep_err = make_config_error( + ConfigErrorCode::limit_exceeded, + "ReloadController: participant budget exceeded"); + break; + } + total_budget += item_budget; + if (pr->view) { + res_map->insert_or_assign(ap.id, pr->view); + } + prepared_list.push_back(std::move(*pr)); + } catch (const std::exception& ex) { + prep_err = make_config_error( + ConfigErrorCode::prepare_failed, ex.what()); + break; + } catch (...) { + prep_err = make_config_error( + ConfigErrorCode::prepare_failed, + "ReloadController: participant prepare threw"); + break; + } + } + + release_inflight(); + + if (prep_err.has_value()) { + for (auto it = prepared_list.rbegin(); + it != prepared_list.rend(); ++it) { + if (it->dispose_async) { + (void)co_await it->dispose_async(); + } + } + co_return Void::Result::fail(std::move(*prep_err)); + } + + PreparedAggregate agg; + agg.values = std::move(cand_ptr); + agg.provenance = merged_ptr->provenance; + if (old_snap.raw) { + agg.changed_keys = + detail::diff_merged_keys(*old_snap.raw, *merged_ptr); + } + agg.raw = std::move(merged_ptr); + agg.resources = std::move(res_map); + agg.staged_changes = std::move(prepared_list); + agg.warnings = std::move(validated->warnings); + co_return agg; + } + + Schema m_schema; + const Void::Time::MonotonicClock* m_clock; + Void::Async::Executor* m_executor{nullptr}; + + detail::AsyncReloadGate m_gate{}; + mutable std::mutex m_pub_mu{}; + Snapshot m_current{}; + std::uint64_t m_generation{0}; + std::vector> m_retention_tokens{}; + bool m_closing{false}; + + std::mutex m_part_mu{}; + std::condition_variable m_part_cv{}; + std::vector m_participants{}; + + std::mutex m_listener_mu{}; + std::vector> m_listeners{}; + std::size_t m_next_listener_id{1}; + + std::mutex m_watch_mu{}; + std::vector m_watch_subs{}; + std::atomic m_watcher_busy{false}; + std::atomic m_watcher_dirty{false}; + std::atomic m_coalesced_events{0}; + }; + +} // namespace Void::Configuration diff --git a/include/Void/Configuration/Schema.hpp b/include/Void/Configuration/Schema.hpp new file mode 100644 index 0000000..553a7ea --- /dev/null +++ b/include/Void/Configuration/Schema.hpp @@ -0,0 +1,1030 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(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 shadowed{}; + bool redacted{false}; + }; + + struct Provenance { + std::unordered_map 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 env_keys{}; + std::string env_prefix{}; + std::vector> entries{}; + std::vector cli_args{}; + std::vector removals{}; + bool is_inline{false}; + }; + + class SourceSet + { + public: + + SourceSet& add_defaults_map( + SourceId id, + std::vector> 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 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> 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 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 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& specs() const noexcept + { + return m_specs; + } + + private: + + std::vector m_specs{}; + }; + + struct MergedEntry { + ValueState state{ValueState::Missing}; + std::string value{}; + SourceLocation location{}; + }; + + struct MergedConfig { + std::map entries{}; + std::shared_ptr provenance{ + std::make_shared()}; + 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 + 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 load_sources( + const SourceSet& sources, const ConfigLimits& limits = {}, + const std::unordered_set& secret_keys = {}, + std::vector* 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 deprecated_message{}; + std::optional int_min{}; + std::optional int_max{}; + std::optional real_min{}; + std::optional real_max{}; + }; + + template struct Validated { + T value{}; + std::shared_ptr provenance{}; + std::vector warnings{}; + std::vector 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 + parse_strict_bool(std::string_view raw); + + [[nodiscard]] Void::Result::Result + parse_strict_i64_or_bytes(std::string_view raw, bool allow_bytes, + bool is_secret); + + [[nodiscard]] Void::Result::Result + parse_strict_u64_or_bytes(std::string_view raw, bool allow_bytes, + bool is_secret); + + [[nodiscard]] Void::Result::Result + 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 class Schema + { + public: + + struct Constraint { + std::string name{}; + std::function(const T&)> check{}; + }; + + explicit Schema(ConfigLimits limits = {}) : m_limits(limits) {} + +#ifdef VOID_HAS_CONFIG_REFLECTION + [[nodiscard]] static Schema + from_reflection(std::string_view prefix = {}, + ConfigLimits limits = {}) + { + Schema s{limits}; + collect_reflection(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(const T&)> fn) + { + m_constraints.push_back( + Constraint{std::move(name), std::move(fn)}); + return *this; + } + + [[nodiscard]] const std::map& + rules() const noexcept + { + return m_rules; + } + + [[nodiscard]] const std::vector& + constraints() const noexcept + { + return m_constraints; + } + + [[nodiscard]] std::unordered_set secret_keys() const + { + std::unordered_set 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 + static void collect_reflection(Schema& s, + std::string_view prefix) + { + template for (constexpr auto m : Void::Meta::members_v) + { + using MT = [:std::meta::type_of(m):]; + constexpr auto ko = Void::Meta::annotation_of(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 && + !BindDetail::Leaf) { + collect_reflection(s, full); + } else { + FieldRule r; + r.key = full; + r.required = Void::Meta::has_annotation(m); + r.secret = Void::Meta::has_annotation(m); + r.restart_required = + Void::Meta::has_annotation(m); + r.is_vector = Void::Meta::is_vector_v; + r.is_optional = Void::Meta::is_optional_v; + if constexpr (constexpr auto dep = + Void::Meta::annotation_of( + m); + dep.has_value()) { + r.deprecated_message = std::string{dep->message.view()}; + } + if constexpr (constexpr auto ir = + Void::Meta::annotation_of(m); + ir.has_value()) { + r.int_min = ir->min; + r.int_max = ir->max; + } + if constexpr (constexpr auto rr = + Void::Meta::annotation_of( + 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 m_rules{}; + std::vector m_constraints{}; + }; + + namespace SchemaDetail + { + template + struct IsDuration : std::false_type { + }; + template + struct IsDuration> : std::true_type { + }; + + template + Void::Result::Result 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) { + 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) { + 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) { +#ifdef VOID_HAS_ENUM_REFLECTION + if (auto e = Void::Detail::enum_parse(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::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(*parsed); + } else if constexpr (std::is_floating_point_v) { + 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(*r); + } else if constexpr (std::is_integral_v && + std::is_signed_v) { + 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::numeric_limits::min()) || + *r > static_cast( + std::numeric_limits::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(*r); + } else if constexpr (std::is_integral_v && + std::is_unsigned_v) { + 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::numeric_limits::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::max(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(*rule->int_max))) { + return fail_cat(ConfigErrorCode::range_error, + "above maximum"); + } + } + return static_cast(*r); + } else { + static_assert(std::is_same_v, + "unsupported strict config field type"); + } + } + } + +#ifdef VOID_HAS_CONFIG_REFLECTION + template + void bind_strict_into(const MergedConfig& cfg, + const Schema& schema, + std::string_view prefix, Agg& out, + std::vector& diags, + std::vector& warnings, + std::unordered_set& 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) + { + using MT = [:std::meta::type_of(m):]; + constexpr auto ko = Void::Meta::annotation_of(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(m); + const bool is_required = + (rule != nullptr && rule->required) || + Void::Meta::has_annotation(m); + + if constexpr (BindDetail::BindableAggregate && + !BindDetail::Leaf) { + bind_strict_into(cfg, schema, full, out.[:m:], + diags, warnings, consumed_keys); + } else if constexpr (Void::Meta::is_optional_v) { + 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(full, it->second, rule); + if (!v) { + push_diag(static_cast( + 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) { + using U = typename MT::value_type; + const std::string item_prefix = full + "."; + std::map 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( + item_prefix + std::to_string(i), + *idx_it->second, rule); + if (!v) { + push_diag(static_cast( + 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(full, it->second, rule); + if (!v) { + push_diag(static_cast( + 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 + [[nodiscard]] Void::Result::Result> + validate(const MergedConfig& cfg, const Schema& schema) + { + Validated result; + result.provenance = cfg.provenance; + std::vector& diags = result.diagnostics; + std::unordered_set consumed_keys; + +#ifdef VOID_HAS_CONFIG_REFLECTION + if constexpr (BindDetail::BindableAggregate) { + SchemaDetail::bind_strict_into( + 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 + [[nodiscard]] Void::Result::Result> + validate(const Config& cfg, const Schema& schema) + { + SourceSet ss; + std::vector> 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(*merged, schema); + } + + template + [[nodiscard]] std::vector detect_restart_required_changes( + const MergedConfig& old_cfg, const MergedConfig& new_cfg, + const Schema& schema) + { + std::vector 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 diff --git a/src/Configuration/Schema.cpp b/src/Configuration/Schema.cpp new file mode 100644 index 0000000..72d891c --- /dev/null +++ b/src/Configuration/Schema.cpp @@ -0,0 +1,766 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__unix__) || defined(__APPLE__) +extern char** environ; // NOLINT +#define VOID_SCHEMA_HAS_ENVIRON 1 +#endif + +namespace Void::Configuration +{ + namespace detail + { + Void::Result::Result parse_strict_bool(std::string_view raw) + { + std::string lower; + lower.reserve(raw.size()); + for (const char c : raw) { + lower += static_cast( + std::tolower(static_cast(c))); + } + if (lower == "true" || lower == "1" || lower == "yes" || + lower == "on") { + return true; + } + if (lower == "false" || lower == "0" || lower == "no" || + lower == "off") { + return false; + } + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, "expected boolean value")); + } + + Void::Result::Result parse_strict_i64_or_bytes( + std::string_view raw, bool allow_bytes, bool is_secret) + { + if (raw.empty()) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, "empty integer value")); + } + std::int64_t exact = 0; + const char* begin = raw.data(); + const char* end = raw.data() + raw.size(); + const auto [ptr, ec] = std::from_chars(begin, end, exact); + if (ec == std::errc{} && ptr == end) { + return exact; + } + if (ec == std::errc::result_out_of_range) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::range_error, + std::string{"signed integer overflow: "} + + redact_display(raw, is_secret))); + } + + if (allow_bytes) { + double num = 0.0; + const auto [bptr, bec] = std::from_chars(begin, end, num); + if (bec == std::errc{} && bptr != begin && std::isfinite(num) && + num >= 0.0) { + std::string_view suffix{bptr, end}; + while (!suffix.empty() && suffix.front() == ' ') { + suffix.remove_prefix(1); + } + double mult = 0.0; + if (suffix == "B" || suffix.empty()) { + 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; + } + if (mult > 0.0) { + const double scaled = num * mult; + if (std::isfinite(scaled) && + scaled <= + static_cast( + std::numeric_limits::max())) { + return static_cast(scaled); + } + return Void::Result::fail(make_config_error( + ConfigErrorCode::range_error, + "byte-size value overflows int64_t")); + } + } + } + + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, + std::string{"not a signed integer or byte size: "} + + redact_display(raw, is_secret))); + } + + Void::Result::Result parse_strict_u64_or_bytes( + std::string_view raw, bool allow_bytes, bool is_secret) + { + if (raw.empty()) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, + "empty unsigned integer value")); + } + std::uint64_t exact = 0; + const char* begin = raw.data(); + const char* end = raw.data() + raw.size(); + const auto [ptr, ec] = std::from_chars(begin, end, exact); + if (ec == std::errc{} && ptr == end) { + return exact; + } + if (ec == std::errc::result_out_of_range) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::range_error, + std::string{"unsigned integer overflow: "} + + redact_display(raw, is_secret))); + } + + if (allow_bytes) { + double num = 0.0; + const auto [bptr, bec] = std::from_chars(begin, end, num); + if (bec == std::errc{} && bptr != begin && std::isfinite(num) && + num >= 0.0) { + std::string_view suffix{bptr, end}; + while (!suffix.empty() && suffix.front() == ' ') { + suffix.remove_prefix(1); + } + double mult = 0.0; + if (suffix == "B" || suffix.empty()) { + 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; + } + if (mult > 0.0) { + const double scaled = num * mult; + if (std::isfinite(scaled) && + scaled < 18446744073709551616.0) { + return static_cast(scaled); + } + return Void::Result::fail(make_config_error( + ConfigErrorCode::range_error, + "byte-size value overflows uint64_t")); + } + } + } + + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, + std::string{"not an unsigned integer or byte size: "} + + redact_display(raw, is_secret))); + } + + Void::Result::Result parse_strict_real(std::string_view raw, + bool is_secret) + { + if (raw.empty()) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, "empty real value")); + } + double val = 0.0; + const char* begin = raw.data(); + const char* end = raw.data() + raw.size(); + const auto [ptr, ec] = std::from_chars(begin, end, val); + if (ec != std::errc{} || ptr != end || !std::isfinite(val)) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::type_mismatch, + std::string{"invalid finite real: "} + + redact_display(raw, is_secret))); + } + return val; + } + + bool try_parse_vector_index(std::string_view suffix, std::size_t& out) + { + if (suffix.empty()) { + return false; + } + if (suffix.size() > 1 && suffix.front() == '0') { + return false; + } + std::size_t idx = 0; + const auto [ptr, ec] = std::from_chars( + suffix.data(), suffix.data() + suffix.size(), idx); + if (ec != std::errc{} || ptr != suffix.data() + suffix.size()) { + return false; + } + out = idx; + return true; + } + } // namespace detail + + namespace + { + int precedence_rank(SourceKind kind) noexcept + { + switch (kind) { + case SourceKind::Defaults: + return 0; + case SourceKind::FileKeyValue: + case SourceKind::FileIni: + case SourceKind::FileJson: + return 1; + case SourceKind::Environment: + return 2; + case SourceKind::CliArgs: + return 3; + } + return 0; + } + + struct EmittedItem { + std::string key{}; + ValueState state{ValueState::Present}; + std::string value{}; + std::uint32_t line{0}; + }; + + Void::Result::Result + flatten_json_checked(const Void::Json::Value& v, + const std::string& prefix, std::size_t depth, + const ConfigLimits& limits, + std::vector& out, + std::unordered_set& dot_paths, + std::unordered_set& nested_paths) + { + if (depth > limits.max_nesting_depth) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: JSON nesting depth exceeds max_nesting_depth")); + } + if (v.is_object()) { + for (const auto& [k, child] : v.as_object()) { + if (k.size() > limits.max_key_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: JSON key exceeds max_key_bytes")); + } + const std::string full = + prefix.empty() ? k : prefix + "." + k; + if (k.find('.') != std::string::npos) { + if (nested_paths.contains(full)) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::key_collision, + "Configuration: key collision between literal dot '" + + full + "' and nested JSON path")); + } + dot_paths.insert(full); + } else if (!prefix.empty()) { + if (dot_paths.contains(full)) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::key_collision, + "Configuration: key collision between nested path '" + + full + "' and literal dotted key")); + } + nested_paths.insert(full); + } + if (auto r = flatten_json_checked( + child, full, depth + 1, limits, out, dot_paths, + nested_paths); + !r) { + return r; + } + } + return {}; + } + if (v.is_array()) { + const auto& arr = v.as_array(); + if (arr.size() > limits.max_vector_items) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: JSON array exceeds max_vector_items")); + } + for (std::size_t i = 0; i < arr.size(); ++i) { + const std::string child_key = + prefix + "." + std::to_string(i); + if (dot_paths.contains(child_key)) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::key_collision, + "Configuration: key collision with dotted path '" + + child_key + "'")); + } + nested_paths.insert(child_key); + if (auto r = flatten_json_checked( + arr[i], child_key, depth + 1, limits, out, + dot_paths, nested_paths); + !r) { + return r; + } + } + return {}; + } + + if (prefix.empty()) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::parse_error, + "Configuration: top-level JSON configuration must be an object")); + } + if (prefix.size() > limits.max_key_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: flattened key exceeds max_key_bytes")); + } + + if (v.is_null()) { + out.push_back(EmittedItem{prefix, ValueState::Null, {}, 0}); + } else if (v.is_string()) { + const auto& s = v.as_string(); + out.push_back(EmittedItem{ + prefix, + s.empty() ? ValueState::Empty : ValueState::Present, s, 0}); + } else if (v.is_bool()) { + out.push_back(EmittedItem{ + prefix, ValueState::Present, + v.as_bool() ? "true" : "false", 0}); + } else if (v.is_int()) { + out.push_back(EmittedItem{ + prefix, ValueState::Present, std::to_string(v.as_int()), 0}); + } else if (v.is_uint()) { + out.push_back(EmittedItem{ + prefix, ValueState::Present, std::to_string(v.as_uint()), + 0}); + } else if (v.is_number()) { + const double d = v.as_number(); + if (!std::isfinite(d)) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::parse_error, + "Configuration: non-finite number for '" + prefix + + "'")); + } + std::string s; + if (!(d == 0.0 && std::signbit(d)) && std::floor(d) == d && + std::abs(d) < 1e15) { + s = std::to_string(static_cast(d)); + } else { + s = std::format("{}", d); + } + out.push_back( + EmittedItem{prefix, ValueState::Present, std::move(s), 0}); + } + return {}; + } + + Void::Result::Result + read_bounded_source_file(const std::filesystem::path& path, + const ConfigLimits& limits) + { + std::error_code ec; + const auto sz = std::filesystem::file_size(path, ec); + if (ec) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::io_error, + "Configuration: cannot stat source file '" + path.string() + + "'")); + } + if (sz > limits.max_source_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: source file '" + path.string() + + "' exceeds max_source_bytes")); + } + auto txt = Void::FileSystem::read_file(path); + if (!txt) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::io_error, + "Configuration: read error on '" + path.string() + "'")); + } + if (txt->size() > limits.max_source_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: source file '" + path.string() + + "' exceeds max_source_bytes")); + } + return *txt; + } + } // namespace + + Void::Result::Result + load_sources(const SourceSet& sources, const ConfigLimits& limits, + const std::unordered_set& secret_keys, + std::vector* diagnostics_out) + { + const auto& specs = sources.specs(); + if (specs.size() > limits.max_sources) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration::load_sources: number of sources exceeds max_sources")); + } + + std::vector order(specs.size()); + std::iota(order.begin(), order.end(), 0); + std::stable_sort(order.begin(), order.end(), [&](std::size_t a, + std::size_t b) { + const int ra = precedence_rank(specs[a].kind); + const int rb = precedence_rank(specs[b].kind); + return ra < rb; + }); + + MergedConfig merged; + std::size_t merged_bytes = 0; + + auto record_diag = [&](const Diagnostic& d) { + if (diagnostics_out != nullptr && + diagnostics_out->size() < limits.max_diagnostics) { + diagnostics_out->push_back(d); + } + }; + + auto apply_item = + [&](const SourceSpec& spec, + const EmittedItem& item) -> Void::Result::Result { + const bool is_secret = secret_keys.contains(item.key); + if (item.key.size() > limits.max_key_bytes) { + Diagnostic d{ConfigErrorCode::limit_exceeded, "limit", + SourceLocation{spec.id, item.key, item.line}, + "Configuration: key exceeds max_key_bytes", + is_secret}; + record_diag(d); + return Void::Result::fail( + make_config_error(d.code, d.message)); + } + if (item.value.size() > limits.max_scalar_bytes) { + Diagnostic d{ + ConfigErrorCode::limit_exceeded, "limit", + SourceLocation{spec.id, item.key, item.line}, + "Configuration: scalar value for '" + item.key + "' (" + + detail::redact_display( + std::to_string(item.value.size()) + "B", + is_secret) + + ") exceeds max_scalar_bytes", + is_secret}; + record_diag(d); + return Void::Result::fail( + make_config_error(d.code, d.message)); + } + + const std::size_t delta = + item.key.size() + (is_secret ? 0 : item.value.size()) + + spec.id.size(); + if (merged_bytes + delta > limits.max_merged_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: merged configuration exceeds max_merged_bytes")); + } + if (!merged.entries.contains(item.key) && + merged.entries.size() >= limits.max_keys) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: key count exceeds max_keys")); + } + merged_bytes += delta; + + const SourceLocation loc{spec.id, item.key, item.line}; + merged.entries[item.key] = + MergedEntry{item.state, item.value, loc}; + + SourceOrigin origin{spec.id, spec.kind, item.line, item.state}; + auto& prov = merged.provenance->entries[item.key]; + if (!prov.key.empty()) { + prov.shadowed.push_back(std::move(prov.winner)); + } else { + prov.key = item.key; + } + prov.winner = std::move(origin); + prov.redacted = prov.redacted || is_secret; + return {}; + }; + + for (const std::size_t idx : order) { + const auto& spec = specs[idx]; + std::vector items; + + for (const auto& rm_key : spec.removals) { + items.push_back(EmittedItem{rm_key, ValueState::Removed, {}, 0}); + } + + switch (spec.kind) { + case SourceKind::Defaults: { + for (const auto& [k, v] : spec.entries) { + items.push_back(EmittedItem{ + k, v.empty() ? ValueState::Empty : ValueState::Present, + v, 0}); + } + break; + } + case SourceKind::FileKeyValue: { + std::string text; + if (spec.is_inline) { + if (spec.inline_text.size() > limits.max_source_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: inline KV exceeds max_source_bytes")); + } + text = spec.inline_text; + } else { + auto r = + read_bounded_source_file(spec.file_path, limits); + if (!r) return Void::Result::fail(std::move(r).error()); + text = std::move(*r); + } + std::size_t pos = 0; + std::uint32_t lineno = 0; + while (pos <= text.size()) { + ++lineno; + const auto nl = text.find('\n', pos); + std::string_view line = + nl == std::string::npos + ? std::string_view{text}.substr(pos) + : std::string_view{text}.substr(pos, nl - pos); + if (!line.empty() && line.back() == '\r') { + line.remove_suffix(1); + } + while (!line.empty() && line.front() == ' ') { + line.remove_prefix(1); + } + if (!line.empty() && line.front() != '#') { + const auto eq = line.find('='); + if (eq == std::string_view::npos) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::parse_error, + std::format( + "Configuration: source '{}' line {}: missing '='", + spec.id, lineno))); + } + auto k = line.substr(0, eq); + while (!k.empty() && k.back() == ' ') { + k.remove_suffix(1); + } + auto v = line.substr(eq + 1); + items.push_back(EmittedItem{ + std::string{k}, + v.empty() ? ValueState::Empty + : ValueState::Present, + std::string{v}, lineno}); + } + if (nl == std::string::npos) break; + pos = nl + 1; + } + break; + } + case SourceKind::FileIni: { + std::string text; + if (spec.is_inline) { + if (spec.inline_text.size() > limits.max_source_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: inline INI exceeds max_source_bytes")); + } + text = spec.inline_text; + } else { + auto r = + read_bounded_source_file(spec.file_path, limits); + if (!r) return Void::Result::fail(std::move(r).error()); + text = std::move(*r); + } + Void::Ini::IniFile ini; + if (auto err = Void::Ini::IniFile::parse(ini, text); + err.has_value()) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::parse_error, + std::format( + "Configuration: INI source '{}' line {}: {}", + spec.id, err->line, err->message))); + } + for (const auto& sec : ini.sections()) { + const auto* tbl = ini.section(sec); + if (tbl == nullptr) continue; + for (const auto& [k, v] : *tbl) { + std::string full = + sec.empty() ? k : sec + "." + k; + items.push_back(EmittedItem{ + std::move(full), + v.empty() ? ValueState::Empty + : ValueState::Present, + v, 0}); + } + } + break; + } + case SourceKind::FileJson: { + std::string text; + if (spec.is_inline) { + if (spec.inline_text.size() > limits.max_source_bytes) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::limit_exceeded, + "Configuration: inline JSON exceeds max_source_bytes")); + } + text = spec.inline_text; + } else { + auto r = + read_bounded_source_file(spec.file_path, limits); + if (!r) return Void::Result::fail(std::move(r).error()); + text = std::move(*r); + } + auto parsed = Void::Json::parse(text); + if (!parsed) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::parse_error, + std::format( + "Configuration: JSON source '{}' line {} col {}: {}", + spec.id, parsed.error().line, + parsed.error().col, parsed.error().message))); + } + if (!parsed->is_object()) { + return Void::Result::fail(make_config_error( + ConfigErrorCode::parse_error, + "Configuration: JSON root must be an object in '" + + spec.id + "'")); + } + std::unordered_set dot_paths; + std::unordered_set nested_paths; + if (auto fr = flatten_json_checked(*parsed, "", 0, limits, + items, dot_paths, + nested_paths); + !fr) { + return Void::Result::fail(std::move(fr).error()); + } + break; + } + case SourceKind::Environment: { + for (const auto& [k, v] : spec.entries) { + items.push_back(EmittedItem{ + k, v.empty() ? ValueState::Empty : ValueState::Present, + v, 0}); + } + for (const auto& k : spec.env_keys) { + if (auto ev = get_env(k); ev) { + items.push_back(EmittedItem{ + k, + ev->empty() ? ValueState::Empty + : ValueState::Present, + std::move(*ev), 0}); + } + } + if (!spec.env_prefix.empty()) { +#ifdef VOID_SCHEMA_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(spec.env_prefix)) { + continue; + } + const auto raw_k = kv.substr( + spec.env_prefix.size(), + eq - spec.env_prefix.size()); + std::string normalized; + normalized.reserve(raw_k.size()); + for (std::size_t i = 0; i < raw_k.size(); ++i) { + if (raw_k[i] == '_' && i + 1 < raw_k.size() && + raw_k[i + 1] == '_') { + normalized += '.'; + ++i; + } else { + normalized += static_cast( + std::tolower( + static_cast( + raw_k[i]))); + } + } + const auto val_sv = kv.substr(eq + 1); + items.push_back(EmittedItem{ + std::move(normalized), + val_sv.empty() ? ValueState::Empty + : ValueState::Present, + std::string{val_sv}, 0}); + } +#endif + } + break; + } + case SourceKind::CliArgs: { + for (std::size_t i = 0; i < spec.cli_args.size(); ++i) { + const std::string_view arg{spec.cli_args[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) { + const auto val_sv = body.substr(eq + 1); + items.push_back(EmittedItem{ + std::string{body.substr(0, eq)}, + val_sv.empty() ? ValueState::Empty + : ValueState::Present, + std::string{val_sv}, 0}); + } else if (i + 1 < spec.cli_args.size() && + !std::string_view{spec.cli_args[i + 1]} + .starts_with("--")) { + const auto val_sv = + std::string_view{spec.cli_args[i + 1]}; + items.push_back(EmittedItem{ + std::string{body}, + val_sv.empty() ? ValueState::Empty + : ValueState::Present, + std::string{val_sv}, 0}); + ++i; + } else { + items.push_back(EmittedItem{ + std::string{body}, ValueState::Present, "true", + 0}); + } + } + break; + } + } + + for (const auto& item : items) { + if (auto r = apply_item(spec, item); !r) { + return Void::Result::fail(std::move(r).error()); + } + } + } + + // Deterministic FNV-1a digest over sorted entries. + std::uint64_t h = 14695981039346656037ULL; + auto mix = [&](std::string_view s) { + for (const char ch : s) { + h ^= static_cast(ch); + h *= 1099511628211ULL; + } + h ^= 0xff; + h *= 1099511628211ULL; + }; + for (const auto& [k, e] : merged.entries) { + mix(k); + h ^= static_cast(e.state); + h *= 1099511628211ULL; + mix(e.value); + } + merged.revision_digest = h; + return merged; + } +} // namespace Void::Configuration diff --git a/src/Configuration/module.cmake b/src/Configuration/module.cmake index a64ad51..6186de5 100644 --- a/src/Configuration/module.cmake +++ b/src/Configuration/module.cmake @@ -1,3 +1,4 @@ void_add_module(Configuration INTERNAL_DEPS Core Functional System Data Time LogState + EXCLUDE_HEADERS Void/Configuration/ReloadController.hpp ) diff --git a/src/ConfigurationAsync/ReloadController.cpp b/src/ConfigurationAsync/ReloadController.cpp new file mode 100644 index 0000000..da7ce2f --- /dev/null +++ b/src/ConfigurationAsync/ReloadController.cpp @@ -0,0 +1,72 @@ +#include + +#include +#include + +namespace Void::Configuration::detail +{ + bool AsyncReloadGate::try_lock() noexcept + { + std::lock_guard lk{mu_}; + if (locked_) { + return false; + } + locked_ = true; + return true; + } + + bool AsyncReloadGate::enqueue_or_acquire(Void::Async::Executor* exec, + std::coroutine_handle<> h) noexcept + { + std::lock_guard lk{mu_}; + if (!locked_) { + locked_ = true; + return false; // do not suspend + } + waiters_.push_back(Waiter{exec, h}); + return true; + } + + void AsyncReloadGate::release() noexcept + { + Waiter next{}; + bool has_next = false; + { + std::lock_guard lk{mu_}; + if (!waiters_.empty()) { + next = waiters_.front(); + waiters_.pop_front(); + has_next = true; + } else { + locked_ = false; + } + } + if (has_next && next.h) { + if (next.exec != nullptr) { + next.exec->post_completion(next.h); + } else { + next.h.resume(); + } + } + } + + std::vector diff_merged_keys(const MergedConfig& old_cfg, + const MergedConfig& new_cfg) + { + std::set out; + for (const auto& [k, ne] : new_cfg.entries) { + const auto it = old_cfg.entries.find(k); + if (it == old_cfg.entries.end() || it->second.state != ne.state || + it->second.value != ne.value) { + out.insert(k); + } + } + for (const auto& [k, oe] : old_cfg.entries) { + if (!new_cfg.entries.contains(k) && + oe.state != ValueState::Missing) { + out.insert(k); + } + } + return std::vector{out.begin(), out.end()}; + } +} // namespace Void::Configuration::detail diff --git a/src/ConfigurationAsync/module.cmake b/src/ConfigurationAsync/module.cmake new file mode 100644 index 0000000..1e9b3f1 --- /dev/null +++ b/src/ConfigurationAsync/module.cmake @@ -0,0 +1,4 @@ +void_add_module(ConfigurationAsync + INTERNAL_DEPS Configuration SystemAsync Async Time Functional LogState + EXTRA_HEADERS Void/Configuration/ReloadController.hpp +) diff --git a/tests/package/ConfigurationAsyncOnly/CMakeLists.txt b/tests/package/ConfigurationAsyncOnly/CMakeLists.txt new file mode 100644 index 0000000..0e8ee40 --- /dev/null +++ b/tests/package/ConfigurationAsyncOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidConfigurationAsyncOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS ConfigurationAsync) + +add_executable(void_configuration_async_only_consumer main.cpp) +target_link_libraries(void_configuration_async_only_consumer PRIVATE Void::ConfigurationAsync) +target_compile_features(void_configuration_async_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME ConfigurationAsyncOnlyConsumer COMMAND void_configuration_async_only_consumer) diff --git a/tests/package/ConfigurationAsyncOnly/main.cpp b/tests/package/ConfigurationAsyncOnly/main.cpp new file mode 100644 index 0000000..e99a0c0 --- /dev/null +++ b/tests/package/ConfigurationAsyncOnly/main.cpp @@ -0,0 +1,20 @@ +#include +#include + +#include + +struct AsyncCfg { + std::string mode{"ok"}; +}; + +int main() +{ + Void::Async::ManualExecutor exec; + Void::Configuration::SourceSet ss; + ss.add_defaults_map("d", {{"mode", "fast"}}); + auto schema = Void::Configuration::Schema::from_reflection(); + auto ctrl = Void::Configuration::ReloadController::create( + schema, std::move(ss), {.executor = &exec}); + if (!ctrl) return 1; + return (*ctrl)->current().values->mode == "fast" ? 0 : 2; +} diff --git a/tests/package/ConfigurationOnly/CMakeLists.txt b/tests/package/ConfigurationOnly/CMakeLists.txt new file mode 100644 index 0000000..4b6d0ca --- /dev/null +++ b/tests/package/ConfigurationOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidConfigurationOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Configuration) + +add_executable(void_configuration_only_consumer main.cpp) +target_link_libraries(void_configuration_only_consumer PRIVATE Void::Configuration) +target_compile_features(void_configuration_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME ConfigurationOnlyConsumer COMMAND void_configuration_only_consumer) diff --git a/tests/package/ConfigurationOnly/main.cpp b/tests/package/ConfigurationOnly/main.cpp new file mode 100644 index 0000000..e56a316 --- /dev/null +++ b/tests/package/ConfigurationOnly/main.cpp @@ -0,0 +1,21 @@ +#include +#include +#include + +#include + +struct MinimalCfg { + [[= Void::Configuration::Required{}]] std::string name; + [[= Void::Configuration::IntRange{1, 100}]] int workers{4}; +}; + +int main() +{ + Void::Configuration::SourceSet ss; + ss.add_defaults_map("def", {{"name", "svc"}, {"workers", "8"}}); + auto schema = Void::Configuration::Schema::from_reflection(); + auto merged = Void::Configuration::load_sources(ss, schema.limits()); + if (!merged) return 1; + auto val = Void::Configuration::validate(*merged, schema); + return val && val->value.name == "svc" && val->value.workers == 8 ? 0 : 2; +} diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 0e11b78..1d00274 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -262,6 +262,26 @@ if(_has_plugin) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) endif() +has_modules(_has_configuration Configuration Core Functional System Data Time LogState) +if(_has_configuration) + run_consumer(ConfigurationOnly "${install_prefix}" "ConfigurationOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + +has_modules(_has_configuration_async ConfigurationAsync Configuration SystemAsync Async Time Functional LogState) +if(_has_configuration_async) + run_consumer(ConfigurationAsyncOnly "${install_prefix}" "ConfigurationAsyncOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/standalone/Configuration/ConfigurationHardening.cpp b/tests/standalone/Configuration/ConfigurationHardening.cpp new file mode 100644 index 0000000..74d4581 --- /dev/null +++ b/tests/standalone/Configuration/ConfigurationHardening.cpp @@ -0,0 +1,256 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace +{ + namespace C = Void::Configuration; + + struct StrictServerConfig { + [[= C::Required{}]] std::string host{}; + [[= C::IntRange{1, 65535}]] int port{8080}; + [[= C::Secret{}]] std::string api_token{}; + [[= C::RestartRequired{}]] std::string bind_interface{"0.0.0.0"}; + [[= C::Deprecated{"use tls_min_version"}]] bool legacy_tls{false}; + std::vector shard_ids{}; + std::optional note{}; + }; +} // namespace + +// @tag reflection +Void::Testing::Test config_schema_precedence_provenance_and_redaction() +{ + C::SourceSet ss; + // Passed out of order on purpose: CLI must win over Env, which wins over + // File, which wins over Defaults. + ss.add_cli_args("cli", {"prog", "--host=cli.internal", "--port", "9090"}); + ss.add_env_map("env", + {{"host", "env.internal"}, + {"port", "7070"}, + {"api_token", "super-secret-value-123"}}); + ss.add_json_text( + "file.json", + R"({"host":"json.internal","port":6060,"shard_ids":[10,20]})"); + ss.add_defaults_map("defaults", + {{"host", "def.internal"}, {"port", "8080"}}); + + auto schema = C::Schema::from_reflection(); + auto merged = C::load_sources(ss, schema.limits(), schema.secret_keys()); + Void::Testing::require(merged.has_value()); + + auto res = C::validate(*merged, schema); + Void::Testing::require(res.has_value()); + Void::Testing::expect_eq(res->value.host, std::string{"cli.internal"}); + Void::Testing::expect_eq(res->value.port, 9090); + Void::Testing::expect_eq(res->value.api_token, + std::string{"super-secret-value-123"}); + Void::Testing::expect_eq(res->value.shard_ids.size(), std::size_t{2}); + Void::Testing::expect_eq(res->value.shard_ids[0], 10); + Void::Testing::expect_eq(res->value.shard_ids[1], 20); + + // Provenance tracks winning origin and shadowed origins with redaction flag. + const auto* host_prov = res->provenance->find("host"); + Void::Testing::require(host_prov != nullptr); + Void::Testing::expect_eq(host_prov->winner.source, std::string{"cli"}); + Void::Testing::expect_eq(host_prov->shadowed.size(), std::size_t{3}); + + const auto* tok_prov = res->provenance->find("api_token"); + Void::Testing::require(tok_prov != nullptr); + Void::Testing::expect(tok_prov->redacted); +} + +// @tag reflection +Void::Testing::Test config_schema_secret_redaction_and_bounds() +{ + auto schema = C::Schema::from_reflection(); + + // Bad secret value (overflow / out-of-range) must redact secret value. + { + C::SourceSet ss; + ss.add_defaults_map("d", {{"host", "h"}}); + // Force a scalar limit violation with secret key. + C::ConfigLimits tiny; + tiny.max_scalar_bytes = 8; + C::SourceSet big_sec; + big_sec.add_defaults_map( + "d", {{"host", "h"}, {"api_token", "VERY_SECRET_XYZ_TOKEN"}}); + auto m = C::load_sources(big_sec, tiny, schema.secret_keys()); + Void::Testing::expect(!m.has_value()); + Void::Testing::expect(m.error().message().find("VERY_SECRET_XYZ") == + std::string::npos); + Void::Testing::expect(m.error().message().find("[REDACTED]") != + std::string::npos); + } + + // Out-of-range port (0 or 70000) fails cleanly with range_error. + { + C::SourceSet ss; + ss.add_defaults_map("d", {{"host", "h"}, {"port", "70000"}}); + auto m = C::load_sources(ss, schema.limits(), schema.secret_keys()); + Void::Testing::require(m.has_value()); + auto v = C::validate(*m, schema); + Void::Testing::expect(!v.has_value()); + Void::Testing::expect_eq( + v.error().code().value, + static_cast(C::ConfigErrorCode::range_error)); + } + + // Exceeding max_source_bytes / max_nesting_depth rejected. + { + Void::FileSystem::TempDir tmp{"void_cfg_limits"}; + const auto file = tmp.path() / "big.json"; + std::string junk(256, 'a'); + Void::Testing::require( + Void::FileSystem::write_file(file, "{\"host\":\"" + junk + "\"}") + .has_value()); + C::ConfigLimits small_src; + small_src.max_source_bytes = 64; + C::SourceSet ss; + ss.add_json_file("f", file); + auto m = C::load_sources(ss, small_src); + Void::Testing::expect(!m.has_value()); + Void::Testing::expect_eq( + m.error().code().value, + static_cast(C::ConfigErrorCode::limit_exceeded)); + } + + { + std::string nested; + for (int i = 0; i < 40; ++i) nested += "{\"a\":"; + nested += "1"; + for (int i = 0; i < 40; ++i) nested += "}"; + C::SourceSet ss; + ss.add_json_text("deep", std::move(nested)); + auto m = C::load_sources(ss); + Void::Testing::expect(!m.has_value()); + Void::Testing::expect_eq( + m.error().code().value, + static_cast(C::ConfigErrorCode::limit_exceeded)); + } +} + +// @tag reflection +Void::Testing::Test config_schema_collisions_gaps_null_empty_and_constraints() +{ + auto schema = C::Schema::from_reflection(); + schema.add_constraint("no_root_interface_in_prod", + [](const StrictServerConfig& cfg) + -> Void::Result::Result { + if (cfg.host == "prod" && cfg.port < 1024) { + return Void::Result::fail( + C::make_config_error( + C::ConfigErrorCode::constraint_failed, + "prod requires non-privileged port")); + } + return {}; + }); + + // Dotted key vs nested path collision rejected. + { + C::SourceSet ss; + ss.add_json_text("coll", + R"({"a":{"b":"nested"},"a.b":"literal-dot"})"); + auto m = C::load_sources(ss); + Void::Testing::expect(!m.has_value()); + Void::Testing::expect_eq( + m.error().code().value, + static_cast(C::ConfigErrorCode::key_collision)); + } + + // Unknown key rejected by default. + { + C::SourceSet ss; + ss.add_defaults_map("d", {{"host", "h"}, {"typo_key", "1"}}); + auto m = C::load_sources(ss); + Void::Testing::require(m.has_value()); + auto v = C::validate(*m, schema); + Void::Testing::expect(!v.has_value()); + Void::Testing::expect_eq( + v.error().code().value, + static_cast(C::ConfigErrorCode::unknown_key)); + } + + // Vector index gap rejected. + { + C::SourceSet ss; + ss.add_defaults_map("d", {{"host", "h"}, + {"shard_ids.0", "1"}, + {"shard_ids.2", "3"}}); + auto m = C::load_sources(ss); + Void::Testing::require(m.has_value()); + auto v = C::validate(*m, schema); + Void::Testing::expect(!v.has_value()); + Void::Testing::expect_eq( + v.error().code().value, + static_cast(C::ConfigErrorCode::vector_gap)); + } + + // Null vs Empty vs Missing vs Removed distinction + no fallback on bad port. + { + C::SourceSet ss; + ss.add_json_text("j", R"({"host":"","port":null,"note":null})"); + auto m = C::load_sources(ss); + Void::Testing::require(m.has_value()); + Void::Testing::expect(m->state_of("host") == C::ValueState::Empty); + Void::Testing::expect(m->state_of("port") == C::ValueState::Null); + Void::Testing::expect(m->state_of("missing_x") == C::ValueState::Missing); + // null on non-optional int fails instead of falling back to 8080. + auto v = C::validate(*m, schema); + Void::Testing::expect(!v.has_value()); + } + + // Removed required field fails required validation. + { + C::SourceSet ss; + ss.add_defaults_map("d", {{"host", "h"}}); + ss.add_removals("r", C::SourceKind::Environment, {"host"}); + auto m = C::load_sources(ss); + Void::Testing::require(m.has_value()); + Void::Testing::expect(m->state_of("host") == C::ValueState::Removed); + auto v = C::validate(*m, schema); + Void::Testing::expect(!v.has_value()); + Void::Testing::expect_eq( + v.error().code().value, + static_cast(C::ConfigErrorCode::missing_required)); + } + + // Cross-field constraint + deprecated warning + restart_required diff. + { + C::SourceSet s1; + s1.add_defaults_map( + "d", {{"host", "prod"}, {"port", "80"}}); + auto m1 = C::load_sources(s1); + auto v1 = C::validate(*m1, schema); + Void::Testing::expect(!v1.has_value()); + Void::Testing::expect_eq( + v1.error().code().value, + static_cast(C::ConfigErrorCode::constraint_failed)); + + C::SourceSet s2; + s2.add_defaults_map("d", {{"host", "prod"}, + {"port", "8443"}, + {"legacy_tls", "true"}, + {"bind_interface", "127.0.0.1"}}); + C::SourceSet s3; + s3.add_defaults_map("d", {{"host", "prod"}, + {"port", "8443"}, + {"bind_interface", "10.0.0.1"}}); + auto m2 = C::load_sources(s2); + auto m3 = C::load_sources(s3); + auto v2 = C::validate(*m2, schema); + Void::Testing::require(v2.has_value()); + Void::Testing::expect(!v2->warnings.empty()); + auto rr = C::detect_restart_required_changes(*m2, *m3, schema); + Void::Testing::expect_eq(rr.size(), std::size_t{1}); + Void::Testing::expect_eq(rr[0], std::string{"bind_interface"}); + } +} diff --git a/tests/standalone/ConfigurationAsync/ConfigurationAsync.cpp b/tests/standalone/ConfigurationAsync/ConfigurationAsync.cpp new file mode 100644 index 0000000..68d27b4 --- /dev/null +++ b/tests/standalone/ConfigurationAsync/ConfigurationAsync.cpp @@ -0,0 +1,340 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace void_cfg_async_test +{ + namespace C = Void::Configuration; + + struct AppSettings { + [[= C::Required{}]] std::string host{"localhost"}; + [[= C::IntRange{1, 65535}]] int port{8080}; + [[= C::RestartRequired{}]] std::string bind_addr{"0.0.0.0"}; + }; + + template + Void::Coro::Task assign_task_result(Void::Coro::Task task, + std::optional* out) + { + *out = co_await task; + } + + template + T drive_task(Void::Async::ManualExecutor& exec, Void::Coro::Task task) + { + std::optional out; + Void::Async::spawn(exec, assign_task_result(std::move(task), &out)); + (void)exec.drain(); + return std::move(*out); + } + + Void::Coro::Task> make_resource_ok( + std::string label, std::atomic* disposes) + { + auto view = std::make_shared(std::move(label)); + C::PreparedChange pc; + pc.view = view; + pc.declared_budget_bytes = 64; + pc.dispose_async = + [disposes]() -> Void::Coro::Task> { + if (disposes != nullptr) { + disposes->fetch_add(1, std::memory_order_relaxed); + } + co_return Void::Result::Result{}; + }; + co_return pc; + } + + Void::Coro::Task> make_resource_fail() + { + co_return Void::Result::fail(C::make_config_error( + C::ConfigErrorCode::prepare_failed, "participant 2 prepare failed")); + } + + Void::Coro::Task, + Void::Result::Result>>> + run_two_reloads_concurrent( + std::shared_ptr> ctrl, + C::SourceSet s1, C::SourceSet s2) + { + auto t1 = ctrl->reload(std::move(s1)); + auto t2 = ctrl->reload(std::move(s2)); + auto r1 = co_await t1; + auto r2 = co_await t2; + co_return Void::Result::Result< + std::pair, + Void::Result::Result>>{ + std::pair{std::move(r1), std::move(r2)}}; + } +} // namespace void_cfg_async_test + +using namespace void_cfg_async_test; + +// @tag reflection +Void::Testing::Test config_async_fallible_factory_and_participant_rollback() +{ + auto schema = C::Schema::from_reflection(); + Void::Async::ManualExecutor exec; + + // Invalid initial config fails controller creation cleanly. + { + C::SourceSet bad; + bad.add_defaults_map("d", {{"host", "h"}, {"port", "99999"}}); + auto failed = C::ReloadController::create( + schema, std::move(bad), {.executor = &exec}); + Void::Testing::expect(!failed.has_value()); + } + + C::SourceSet init; + init.add_defaults_map("d", {{"host", "v1"}, {"port", "8080"}}); + auto ctrl_res = C::ReloadController::create( + schema, std::move(init), {.executor = &exec}); + Void::Testing::require(ctrl_res.has_value()); + auto ctrl = std::move(*ctrl_res); + + std::atomic disposals{0}; + Void::Testing::require( + ctrl->register_participant( + "p1", 64, + [&](const C::Snapshot&, + const std::shared_ptr& cand, + Void::Async::OperationOptions) { + return make_resource_ok(cand->host + ":" + + std::to_string(cand->port), + &disposals); + }) + .has_value()); + Void::Testing::require( + ctrl->register_participant( + "p2", 64, + [](const C::Snapshot&, + const std::shared_ptr&, + Void::Async::OperationOptions) { + return make_resource_fail(); + }) + .has_value()); + + // Reload fails in p2 -> must dispose p1 and keep generation 1 intact. + { + C::SourceSet s2; + s2.add_defaults_map("d", {{"host", "v2"}, {"port", "9090"}}); + auto r = drive_task(exec, ctrl->reload(std::move(s2))); + Void::Testing::expect(!r.has_value()); + Void::Testing::expect_eq(disposals.load(), 1); + auto snap = ctrl->current(); + Void::Testing::expect_eq(snap.generation, std::uint64_t{1}); + Void::Testing::expect_eq(snap.values->host, std::string{"v1"}); + } + + // Unregister p2 and commit v2 with notification throw isolation + + // post-commit stop observation + restart-required check. + ctrl->unregister_participant("p2"); + ctrl->on_committed( + [](const C::Snapshot&, const C::ReloadReport&) { + throw std::runtime_error("observer failure"); + }); + + std::stop_source ss; + Void::Testing::require( + ctrl->register_participant( + "p_stop", 64, + [&](const C::Snapshot&, + const std::shared_ptr&, + Void::Async::OperationOptions) + -> Void::Coro::Task> { + // Request stop only inside the second reload if flagged. + co_return co_await make_resource_ok("ok", nullptr); + }) + .has_value()); + + { + C::SourceSet s2; + s2.add_defaults_map("d", {{"host", "v2"}, {"port", "9090"}}); + auto r = drive_task(exec, ctrl->reload(std::move(s2))); + Void::Testing::require(r.has_value()); + Void::Testing::expect(r->committed); + Void::Testing::expect_eq(r->generation, std::uint64_t{2}); + Void::Testing::expect_eq(r->notification_errors.size(), std::size_t{1}); + auto snap = ctrl->current(); + auto view = snap.resource("p1"); + Void::Testing::require(view != nullptr); + Void::Testing::expect_eq(*view, std::string{"v2:9090"}); + } + + // Restart-required key change preserves generation 2 and reports pending. + { + C::SourceSet s_rr; + s_rr.add_defaults_map( + "d", {{"host", "v3"}, {"port", "9091"}, {"bind_addr", "127.0.0.1"}}); + auto r = drive_task(exec, ctrl->reload(std::move(s_rr))); + Void::Testing::require(r.has_value()); + Void::Testing::expect(!r->committed); + Void::Testing::expect(r->restart_required); + Void::Testing::expect_eq(r->generation, std::uint64_t{2}); + Void::Testing::expect_eq(ctrl->current().values->host, + std::string{"v2"}); + } + + ctrl->close_and_join(); +} + +// @tag reflection +Void::Testing::Test config_async_retention_precommit_cancel_and_concurrent_order() +{ + auto schema = C::Schema::from_reflection(); + Void::Async::ManualExecutor exec; + + C::SourceSet init; + init.add_defaults_map("d", {{"host", "g1"}, {"port", "8001"}}); + auto ctrl = + C::ReloadController::create(schema, std::move(init), + {.executor = &exec}) + .value(); + + std::vector> pinned; + pinned.push_back(ctrl->current()); // gen 1 + for (int i = 2; i <= 4; ++i) { + C::SourceSet s; + s.add_defaults_map("d", {{"host", "g" + std::to_string(i)}, + {"port", std::to_string(8000 + i)}}); + auto r = drive_task(exec, ctrl->reload(std::move(s))); + Void::Testing::require(r.has_value()); + pinned.push_back(ctrl->current()); + } + Void::Testing::expect_eq(ctrl->retained_generation_count(), std::size_t{4}); + + // 5th generation rejected while 4 snapshots remain pinned. + { + C::SourceSet s5; + s5.add_defaults_map("d", {{"host", "g5"}, {"port", "8005"}}); + auto r5 = drive_task(exec, ctrl->reload(std::move(s5))); + Void::Testing::expect(!r5.has_value()); + Void::Testing::expect_eq( + r5.error().code().value, + static_cast(C::ConfigErrorCode::retention_limit)); + } + + pinned.erase(pinned.begin()); // Drop gen 1 -> 3 live + + // Pre-commit cancellation disposes candidate and preserves gen 4. + std::stop_source ss; + ss.request_stop(); + { + C::SourceSet sc; + sc.add_defaults_map("d", {{"host", "cancel"}, {"port", "8006"}}); + Void::Async::OperationOptions opts; + opts.stop = ss.get_token(); + auto rc = drive_task(exec, ctrl->reload(std::move(sc), opts)); + Void::Testing::expect(!rc.has_value()); + Void::Testing::expect_eq( + rc.error().code().value, + static_cast(C::ConfigErrorCode::cancelled)); + Void::Testing::expect_eq(ctrl->current().values->host, + std::string{"g4"}); + } + + // Concurrent reloads serialize cleanly within the retention budget. + pinned.clear(); + { + C::SourceSet a, b; + a.add_defaults_map("d", {{"host", "c1"}, {"port", "8011"}}); + b.add_defaults_map("d", {{"host", "c2"}, {"port", "8012"}}); + auto both = drive_task( + exec, run_two_reloads_concurrent(ctrl, std::move(a), std::move(b))); + Void::Testing::require(both.has_value()); + Void::Testing::require(both->first.has_value()); + Void::Testing::require(both->second.has_value()); + Void::Testing::expect(both->second->generation > + both->first->generation); + } +} + +// @tag reflection +Void::Testing::Test config_async_watcher_coalescing_and_prepare_external() +{ + Void::FileSystem::TempDir tmp{"void_cfg_async_watch"}; + const auto cfg_path = tmp.path() / "app.json"; + Void::Testing::require( + Void::FileSystem::write_file(cfg_path, R"({"host":"init","port":8080})") + .has_value()); + + auto schema = C::Schema::from_reflection(); + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock; + Void::SystemAsync::WatcherService watcher{ + exec, + Void::SystemAsync::WatcherLimits{ + .poll_interval = std::chrono::milliseconds{10}, + .debounce_polls = 1}, + clock}; + + auto build_sources = [&]() { + C::SourceSet ss; + ss.add_json_file("app", cfg_path); + return ss; + }; + auto ctrl = + C::ReloadController::create(schema, build_sources(), + {.clock = &clock, + .executor = &exec}) + .value(); + + std::atomic commits{0}; + ctrl->on_committed([&](const C::Snapshot&, + const C::ReloadReport&) { + commits.fetch_add(1, std::memory_order_relaxed); + }); + Void::Testing::require( + ctrl->attach_watcher(watcher, {cfg_path}, build_sources, exec) + .has_value()); + + // Overwrite with invalid JSON first (must keep old), then valid edit. + Void::Testing::require( + Void::FileSystem::write_file(cfg_path, "{broken").has_value()); + watcher.poll_once(); + (void)exec.drain(); + Void::Testing::expect_eq(ctrl->current().values->host, + std::string{"init"}); + + Void::Testing::require( + Void::FileSystem::write_file(cfg_path, + R"({"host":"watched","port":8099})") + .has_value()); + watcher.poll_once(); + (void)exec.drain(); + Void::Testing::expect_eq(ctrl->current().values->host, + std::string{"watched"}); + Void::Testing::expect_eq(ctrl->current().values->port, 8099); + Void::Testing::expect(commits.load() >= 1); + + // Prepare-only external coordinator port leaves controller unchanged. + { + C::SourceSet ext; + ext.add_defaults_map("d", {{"host", "staged_ext"}, {"port", "8111"}}); + auto prep = drive_task(exec, ctrl->prepare_external(std::move(ext))); + Void::Testing::require(prep.has_value()); + Void::Testing::expect_eq(prep->values->host, + std::string{"staged_ext"}); + Void::Testing::expect_eq(ctrl->current().values->host, + std::string{"watched"}); + (void)drive_task(exec, prep->dispose_all()); + } + + ctrl->close_and_join(); + Void::Testing::expect(watcher.shutdown().has_value()); +}