feat(configuration): bounded schemas, provenance/redaction, and async transactional ReloadController

This commit is contained in:
faumaray committed 2026-11-26 16:30:30 +03:00
1 parent a24e086e47
commit 1dc51d5c43
14 files changed
+3351

No files matched your search

+15
View File
@@ -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