feat(configuration): bounded schemas, provenance/redaction, and async transactional ReloadController
This commit is contained in:
1 parent
a24e086e47
commit
1dc51d5c43
14 files changed
+3351
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -0,0 +1,784 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Configuration/Schema.hpp>
|
||||
#include <Void/System/AsyncWatcher.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <coroutine>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <exception>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Configuration
|
||||
{
|
||||
struct PreparedChange {
|
||||
std::shared_ptr<const void> view{};
|
||||
std::size_t declared_budget_bytes{0};
|
||||
std::function<Void::Coro::Task<Void::Result::Result<void>>()>
|
||||
dispose_async{};
|
||||
};
|
||||
|
||||
template <typename T> struct Snapshot {
|
||||
std::uint64_t generation{0};
|
||||
std::shared_ptr<const T> values{};
|
||||
std::shared_ptr<const Provenance> provenance{};
|
||||
std::shared_ptr<const MergedConfig> raw{};
|
||||
std::shared_ptr<
|
||||
const std::unordered_map<std::string, std::shared_ptr<const void>>>
|
||||
resources{};
|
||||
std::shared_ptr<const void> retention_token{};
|
||||
|
||||
template <typename R>
|
||||
[[nodiscard]] std::shared_ptr<const R>
|
||||
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<const R>(it->second);
|
||||
}
|
||||
|
||||
[[nodiscard]] explicit operator bool() const noexcept
|
||||
{
|
||||
return values != nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> struct PreparedAggregate {
|
||||
std::shared_ptr<const T> values{};
|
||||
std::shared_ptr<const Provenance> provenance{};
|
||||
std::shared_ptr<const MergedConfig> raw{};
|
||||
std::shared_ptr<
|
||||
const std::unordered_map<std::string, std::shared_ptr<const void>>>
|
||||
resources{};
|
||||
std::vector<PreparedChange> staged_changes{};
|
||||
std::vector<std::string> changed_keys{};
|
||||
std::vector<std::string> warnings{};
|
||||
|
||||
Void::Coro::Task<Void::Result::Result<void>> 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<void>{};
|
||||
}
|
||||
};
|
||||
|
||||
struct ReloadReport {
|
||||
std::uint64_t generation{0};
|
||||
bool committed{false};
|
||||
bool restart_required{false};
|
||||
std::vector<std::string> restart_required_keys{};
|
||||
bool stop_observed_after_commit{false};
|
||||
std::vector<std::string> changed_keys{};
|
||||
std::vector<Void::Result::Error> notification_errors{};
|
||||
std::vector<std::string> 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<Waiter> waiters_{};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::vector<std::string>
|
||||
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 <typename T>
|
||||
class ReloadController
|
||||
: public std::enable_shared_from_this<ReloadController<T>>
|
||||
{
|
||||
public:
|
||||
|
||||
using PrepareFn = std::function<
|
||||
Void::Coro::Task<Void::Result::Result<PreparedChange>>(
|
||||
const Snapshot<T>& old_snapshot,
|
||||
const std::shared_ptr<const T>& candidate,
|
||||
Void::Async::OperationOptions options)>;
|
||||
|
||||
using CommitListener =
|
||||
std::function<void(const Snapshot<T>& snapshot,
|
||||
const ReloadReport& report)>;
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<
|
||||
std::shared_ptr<ReloadController<T>>>
|
||||
create(Schema<T> 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<T>(*merged, schema);
|
||||
if (!validated) {
|
||||
return Void::Result::fail(std::move(validated).error());
|
||||
}
|
||||
|
||||
auto ctrl = std::shared_ptr<ReloadController<T>>(
|
||||
new ReloadController<T>(std::move(schema), options));
|
||||
auto merged_ptr =
|
||||
std::make_shared<const MergedConfig>(std::move(*merged));
|
||||
auto val_ptr =
|
||||
std::make_shared<const T>(std::move(validated->value));
|
||||
auto res_ptr = std::make_shared<const std::unordered_map<
|
||||
std::string, std::shared_ptr<const void>>>();
|
||||
auto tok = std::make_shared<const int>(1);
|
||||
ctrl->m_retention_tokens.push_back(tok);
|
||||
ctrl->m_current = Snapshot<T>{
|
||||
.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<T> 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<void>
|
||||
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<PreparedAggregate<T>>>
|
||||
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<Void::Result::Result<ReloadReport>>
|
||||
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<T> 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<std::string> 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<const int>(1);
|
||||
Snapshot<T> 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<T> 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<T>{};
|
||||
} 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<T>{};
|
||||
|
||||
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<CommitListener> 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<void> attach_watcher(
|
||||
Void::SystemAsync::WatcherService& watcher,
|
||||
std::vector<std::filesystem::path> paths,
|
||||
std::function<SourceSet()> 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<ReloadController<T>> 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<Void::SystemAsync::WatchSubscription> 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<Void::SystemAsync::WatchSubscription> 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<T> 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<void> run_watch_reload_task(
|
||||
std::weak_ptr<ReloadController<T>> weak_self,
|
||||
std::function<SourceSet()> 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<SourceSet()>& build,
|
||||
Void::Async::Executor& exec)
|
||||
{
|
||||
Void::Async::spawn(
|
||||
exec, run_watch_reload_task(this->weak_from_this(), build,
|
||||
&exec));
|
||||
}
|
||||
|
||||
Void::Coro::Task<Void::Result::Result<PreparedAggregate<T>>>
|
||||
prepare_candidate(SourceSet sources,
|
||||
const Snapshot<T>& old_snap,
|
||||
Void::Async::OperationOptions opts,
|
||||
std::vector<std::string>* 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<T>(*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<T>(
|
||||
*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<const MergedConfig>(std::move(*merged));
|
||||
auto cand_ptr =
|
||||
std::make_shared<const T>(std::move(validated->value));
|
||||
auto res_map = std::make_shared<
|
||||
std::unordered_map<std::string, std::shared_ptr<const void>>>();
|
||||
std::vector<PreparedChange> 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<ActivePart> 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<Void::Result::Error> 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<T> 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<T> 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<T> m_current{};
|
||||
std::uint64_t m_generation{0};
|
||||
std::vector<std::weak_ptr<const void>> m_retention_tokens{};
|
||||
bool m_closing{false};
|
||||
|
||||
std::mutex m_part_mu{};
|
||||
std::condition_variable m_part_cv{};
|
||||
std::vector<ParticipantEntry> m_participants{};
|
||||
|
||||
std::mutex m_listener_mu{};
|
||||
std::vector<std::pair<std::size_t, CommitListener>> m_listeners{};
|
||||
std::size_t m_next_listener_id{1};
|
||||
|
||||
std::mutex m_watch_mu{};
|
||||
std::vector<Void::SystemAsync::WatchSubscription> m_watch_subs{};
|
||||
std::atomic<bool> m_watcher_busy{false};
|
||||
std::atomic<bool> m_watcher_dirty{false};
|
||||
std::atomic<std::size_t> m_coalesced_events{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Configuration
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,766 @@
|
||||
#include <Void/Configuration/Schema.hpp>
|
||||
|
||||
#include <Void/Data/Ini.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <charconv>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <limits>
|
||||
#include <numeric>
|
||||
#include <system_error>
|
||||
|
||||
#if defined(__unix__) || defined(__APPLE__)
|
||||
extern char** environ; // NOLINT
|
||||
#define VOID_SCHEMA_HAS_ENVIRON 1
|
||||
#endif
|
||||
|
||||
namespace Void::Configuration
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
Void::Result::Result<bool> parse_strict_bool(std::string_view raw)
|
||||
{
|
||||
std::string lower;
|
||||
lower.reserve(raw.size());
|
||||
for (const char c : raw) {
|
||||
lower += static_cast<char>(
|
||||
std::tolower(static_cast<unsigned char>(c)));
|
||||
}
|
||||
if (lower == "true" || lower == "1" || lower == "yes" ||
|
||||
lower == "on") {
|
||||
return 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<std::int64_t> 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<double>(
|
||||
std::numeric_limits<std::int64_t>::max())) {
|
||||
return static_cast<std::int64_t>(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<std::uint64_t> 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<std::uint64_t>(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<double> 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<void>
|
||||
flatten_json_checked(const Void::Json::Value& v,
|
||||
const std::string& prefix, std::size_t depth,
|
||||
const ConfigLimits& limits,
|
||||
std::vector<EmittedItem>& out,
|
||||
std::unordered_set<std::string>& dot_paths,
|
||||
std::unordered_set<std::string>& 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<long long>(d));
|
||||
} else {
|
||||
s = std::format("{}", d);
|
||||
}
|
||||
out.push_back(
|
||||
EmittedItem{prefix, ValueState::Present, std::move(s), 0});
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string>
|
||||
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<MergedConfig>
|
||||
load_sources(const SourceSet& sources, const ConfigLimits& limits,
|
||||
const std::unordered_set<std::string>& secret_keys,
|
||||
std::vector<Diagnostic>* 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<std::size_t> 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<void> {
|
||||
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<EmittedItem> 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<std::string> dot_paths;
|
||||
std::unordered_set<std::string> 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<char>(
|
||||
std::tolower(
|
||||
static_cast<unsigned char>(
|
||||
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<unsigned char>(ch);
|
||||
h *= 1099511628211ULL;
|
||||
}
|
||||
h ^= 0xff;
|
||||
h *= 1099511628211ULL;
|
||||
};
|
||||
for (const auto& [k, e] : merged.entries) {
|
||||
mix(k);
|
||||
h ^= static_cast<std::uint64_t>(e.state);
|
||||
h *= 1099511628211ULL;
|
||||
mix(e.value);
|
||||
}
|
||||
merged.revision_digest = h;
|
||||
return merged;
|
||||
}
|
||||
} // namespace Void::Configuration
|
||||
@@ -1,3 +1,4 @@
|
||||
void_add_module(Configuration
|
||||
INTERNAL_DEPS Core Functional System Data Time LogState
|
||||
EXCLUDE_HEADERS Void/Configuration/ReloadController.hpp
|
||||
)
|
||||
@@ -0,0 +1,72 @@
|
||||
#include <Void/Configuration/ReloadController.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <set>
|
||||
|
||||
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<std::string> diff_merged_keys(const MergedConfig& old_cfg,
|
||||
const MergedConfig& new_cfg)
|
||||
{
|
||||
std::set<std::string> 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<std::string>{out.begin(), out.end()};
|
||||
}
|
||||
} // namespace Void::Configuration::detail
|
||||
@@ -0,0 +1,4 @@
|
||||
void_add_module(ConfigurationAsync
|
||||
INTERNAL_DEPS Configuration SystemAsync Async Time Functional LogState
|
||||
EXTRA_HEADERS Void/Configuration/ReloadController.hpp
|
||||
)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,20 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Configuration/ReloadController.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
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<AsyncCfg>::from_reflection();
|
||||
auto ctrl = Void::Configuration::ReloadController<AsyncCfg>::create(
|
||||
schema, std::move(ss), {.executor = &exec});
|
||||
if (!ctrl) return 1;
|
||||
return (*ctrl)->current().values->mode == "fast" ? 0 : 2;
|
||||
}
|
||||
@@ -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)
|
||||
@@ -0,0 +1,21 @@
|
||||
#include <Void/Configuration/Bind.hpp>
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Configuration/Schema.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
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<MinimalCfg>::from_reflection();
|
||||
auto merged = Void::Configuration::load_sources(ss, schema.limits());
|
||||
if (!merged) return 1;
|
||||
auto val = Void::Configuration::validate<MinimalCfg>(*merged, schema);
|
||||
return val && val->value.name == "svc" && val->value.workers == 8 ? 0 : 2;
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
#include <Void/Configuration/Bind.hpp>
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Configuration/Schema.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<int> shard_ids{};
|
||||
std::optional<std::string> 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<StrictServerConfig>::from_reflection();
|
||||
auto merged = C::load_sources(ss, schema.limits(), schema.secret_keys());
|
||||
Void::Testing::require(merged.has_value());
|
||||
|
||||
auto res = C::validate<StrictServerConfig>(*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<StrictServerConfig>::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<StrictServerConfig>(*m, schema);
|
||||
Void::Testing::expect(!v.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
v.error().code().value,
|
||||
static_cast<std::int32_t>(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<std::int32_t>(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<std::int32_t>(C::ConfigErrorCode::limit_exceeded));
|
||||
}
|
||||
}
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test config_schema_collisions_gaps_null_empty_and_constraints()
|
||||
{
|
||||
auto schema = C::Schema<StrictServerConfig>::from_reflection();
|
||||
schema.add_constraint("no_root_interface_in_prod",
|
||||
[](const StrictServerConfig& cfg)
|
||||
-> Void::Result::Result<void> {
|
||||
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<std::int32_t>(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<StrictServerConfig>(*m, schema);
|
||||
Void::Testing::expect(!v.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
v.error().code().value,
|
||||
static_cast<std::int32_t>(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<StrictServerConfig>(*m, schema);
|
||||
Void::Testing::expect(!v.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
v.error().code().value,
|
||||
static_cast<std::int32_t>(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<StrictServerConfig>(*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<StrictServerConfig>(*m, schema);
|
||||
Void::Testing::expect(!v.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
v.error().code().value,
|
||||
static_cast<std::int32_t>(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<StrictServerConfig>(*m1, schema);
|
||||
Void::Testing::expect(!v1.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
v1.error().code().value,
|
||||
static_cast<std::int32_t>(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<StrictServerConfig>(*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"});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Configuration/ReloadController.hpp>
|
||||
#include <Void/System/AsyncWatcher.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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 <typename T>
|
||||
Void::Coro::Task<void> assign_task_result(Void::Coro::Task<T> task,
|
||||
std::optional<T>* out)
|
||||
{
|
||||
*out = co_await task;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T drive_task(Void::Async::ManualExecutor& exec, Void::Coro::Task<T> task)
|
||||
{
|
||||
std::optional<T> out;
|
||||
Void::Async::spawn(exec, assign_task_result(std::move(task), &out));
|
||||
(void)exec.drain();
|
||||
return std::move(*out);
|
||||
}
|
||||
|
||||
Void::Coro::Task<Void::Result::Result<C::PreparedChange>> make_resource_ok(
|
||||
std::string label, std::atomic<int>* disposes)
|
||||
{
|
||||
auto view = std::make_shared<std::string>(std::move(label));
|
||||
C::PreparedChange pc;
|
||||
pc.view = view;
|
||||
pc.declared_budget_bytes = 64;
|
||||
pc.dispose_async =
|
||||
[disposes]() -> Void::Coro::Task<Void::Result::Result<void>> {
|
||||
if (disposes != nullptr) {
|
||||
disposes->fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
co_return Void::Result::Result<void>{};
|
||||
};
|
||||
co_return pc;
|
||||
}
|
||||
|
||||
Void::Coro::Task<Void::Result::Result<C::PreparedChange>> 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<std::pair<
|
||||
Void::Result::Result<C::ReloadReport>,
|
||||
Void::Result::Result<C::ReloadReport>>>>
|
||||
run_two_reloads_concurrent(
|
||||
std::shared_ptr<C::ReloadController<AppSettings>> 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<C::ReloadReport>,
|
||||
Void::Result::Result<C::ReloadReport>>>{
|
||||
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<AppSettings>::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<AppSettings>::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<AppSettings>::create(
|
||||
schema, std::move(init), {.executor = &exec});
|
||||
Void::Testing::require(ctrl_res.has_value());
|
||||
auto ctrl = std::move(*ctrl_res);
|
||||
|
||||
std::atomic<int> disposals{0};
|
||||
Void::Testing::require(
|
||||
ctrl->register_participant(
|
||||
"p1", 64,
|
||||
[&](const C::Snapshot<AppSettings>&,
|
||||
const std::shared_ptr<const AppSettings>& 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<AppSettings>&,
|
||||
const std::shared_ptr<const AppSettings>&,
|
||||
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<AppSettings>&, 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<AppSettings>&,
|
||||
const std::shared_ptr<const AppSettings>&,
|
||||
Void::Async::OperationOptions)
|
||||
-> Void::Coro::Task<Void::Result::Result<C::PreparedChange>> {
|
||||
// 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<std::string>("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<AppSettings>::from_reflection();
|
||||
Void::Async::ManualExecutor exec;
|
||||
|
||||
C::SourceSet init;
|
||||
init.add_defaults_map("d", {{"host", "g1"}, {"port", "8001"}});
|
||||
auto ctrl =
|
||||
C::ReloadController<AppSettings>::create(schema, std::move(init),
|
||||
{.executor = &exec})
|
||||
.value();
|
||||
|
||||
std::vector<C::Snapshot<AppSettings>> 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<std::int32_t>(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<std::int32_t>(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<AppSettings>::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<AppSettings>::create(schema, build_sources(),
|
||||
{.clock = &clock,
|
||||
.executor = &exec})
|
||||
.value();
|
||||
|
||||
std::atomic<int> commits{0};
|
||||
ctrl->on_committed([&](const C::Snapshot<AppSettings>&,
|
||||
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());
|
||||
}
|
||||
Reference in new issue
Block a user