Files
Library/tests/standalone/ConfigurationAsync/ConfigurationAsync.cpp
T

342 lines
11 KiB
C++

// @requires-reflection
#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());
}