feat(discovery): implement P3 S-DISCOVERY-01..04 Discovery catalog and optional DiscoveryRpc adapter

This commit is contained in:
faumaray committed 2026-11-27 05:25:43 +03:00
1 parent 0cf187d664
commit ec8c0bd40a
12 files changed
+2686

No files matched your search

@@ -0,0 +1,14 @@
cmake_minimum_required(VERSION 4.0)
project(VoidDiscoveryOnlyConsumer LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
find_package(Void REQUIRED CONFIG COMPONENTS Discovery)
add_executable(discovery_only main.cpp)
target_link_libraries(discovery_only PRIVATE Void::Discovery)
enable_testing()
add_test(NAME discovery_only COMMAND discovery_only)
+24
View File
@@ -0,0 +1,24 @@
#include <Void/Discovery/Catalog.hpp>
#include <cstdlib>
int main()
{
Void::Discovery::Catalog catalog{};
Void::Discovery::EndpointRecord rec{};
rec.service = "svc";
rec.instance = "i-1";
rec.endpoint.scheme = "http";
rec.endpoint.host = "127.0.0.1";
rec.endpoint.port = 8080;
auto rev = catalog.replace_static({rec});
if (!rev.has_value() || *rev != 1U) {
return EXIT_FAILURE;
}
auto snap = catalog.resolve("svc");
if (!snap.has_value() || snap->records.size() != 1U) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
+5
View File
@@ -318,6 +318,11 @@ if(_has_rpc)
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
has_modules(_has_discovery Discovery Core Functional Time Async)
if(_has_discovery)
run_consumer(DiscoveryOnly "${install_prefix}" "DiscoveryOnly" ${_no_external_deps})
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)
+278
View File
@@ -0,0 +1,278 @@
#include <Void/Async/Executor.hpp>
#include <Void/Discovery/Catalog.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <string>
#include <thread>
#include <vector>
namespace
{
Void::Discovery::EndpointRecord make_record(std::string svc,
std::string inst,
std::string host = "127.0.0.1",
std::uint16_t port = 8080,
std::uint32_t weight = 1)
{
Void::Discovery::EndpointRecord r{};
r.service = std::move(svc);
r.instance = std::move(inst);
r.endpoint.scheme = "http";
r.endpoint.host = std::move(host);
r.endpoint.port = port;
r.weight = weight;
r.ready = true;
return r;
}
} // namespace
Void::Testing::Test discovery_atomic_static_replacement_and_validation()
{
using namespace Void::Discovery;
Catalog catalog{};
auto good = catalog.replace_static({
make_record("orders", "inst-b", "10.0.0.2", 8080, 2),
make_record("orders", "inst-a", "10.0.0.1", 8080, 1),
});
Void::Testing::require(good.has_value());
Void::Testing::expect_eq(*good, 1ULL);
auto snap = catalog.resolve("orders");
Void::Testing::require(snap.has_value());
Void::Testing::expect_eq(snap->revision, 1ULL);
Void::Testing::expect_eq(snap->provider_generation, 1ULL);
Void::Testing::require(snap->records.size() == 2U);
// Deterministic sorted order by instance identity.
Void::Testing::expect_eq(snap->records[0].instance, std::string{"inst-a"});
Void::Testing::expect_eq(snap->records[1].instance, std::string{"inst-b"});
// Duplicate service+instance in candidate must reject atomically and keep
// active revision unchanged.
auto dup = catalog.replace_static({
make_record("orders", "inst-x", "10.0.0.9", 8080),
make_record("orders", "inst-x", "10.0.0.10", 8080),
});
Void::Testing::expect(!dup.has_value());
Void::Testing::expect_eq(
dup.error().code().value,
static_cast<std::int32_t>(DiscoveryErrorCode::Conflict));
Void::Testing::expect_eq(catalog.revision(), 1ULL);
// Invalid metadata / zero port rejected atomically.
auto bad_port = make_record("orders", "inst-c", "10.0.0.3", 0);
auto bad_res = catalog.replace_static({bad_port});
Void::Testing::expect(!bad_res.has_value());
Void::Testing::expect_eq(catalog.revision(), 1ULL);
auto bad_meta = make_record("orders", "inst-c", "10.0.0.3", 8080);
bad_meta.attributes["k"] = std::string(5000, 'x');
auto bad_meta_res = catalog.replace_static({bad_meta});
Void::Testing::expect(!bad_meta_res.has_value());
Void::Testing::expect_eq(
bad_meta_res.error().code().value,
static_cast<std::int32_t>(DiscoveryErrorCode::LimitExceeded));
Void::Testing::expect_eq(catalog.revision(), 1ULL);
// Active snapshot completely preserved.
auto after = catalog.resolve("orders");
Void::Testing::require(after.has_value());
Void::Testing::expect_eq(after->records.size(), 2ULL);
Void::Testing::expect_eq(after->records[0].instance, std::string{"inst-a"});
}
Void::Testing::Test discovery_local_registration_leases_conflict_and_expiry()
{
using namespace Void::Discovery;
using namespace std::chrono_literals;
Void::Time::ManualClock clock{};
Catalog catalog{CatalogOptions{.clock = &clock}};
// Zero TTL is invalid, never an undocumented permanent registration.
auto zero_ttl = catalog.register_local(
make_record("auth", "node-1"), LeasePolicy::with_ttl(0ms));
Void::Testing::expect(!zero_ttl.has_value());
Void::Testing::expect_eq(
zero_ttl.error().code().value,
static_cast<std::int32_t>(DiscoveryErrorCode::InvalidArgument));
auto reg1 = catalog.register_local(
make_record("auth", "node-1", "10.0.1.1", 9000),
LeasePolicy::with_ttl(30s, 10s));
Void::Testing::require(reg1.has_value());
Void::Testing::expect(reg1->active());
// Duplicate registration conflicts without stealing the first handle.
auto dup = catalog.register_local(
make_record("auth", "node-1", "10.0.1.2", 9001),
LeasePolicy::unleased());
Void::Testing::expect(!dup.has_value());
Void::Testing::expect_eq(
dup.error().code().value,
static_cast<std::int32_t>(DiscoveryErrorCode::Conflict));
ManagedLeaseRenewer renewer{*reg1, 10s, &clock};
Void::Testing::expect(!renewer.due());
Void::Testing::require(clock.advance(10s).has_value());
Void::Testing::expect(renewer.due());
auto ticked = renewer.tick();
Void::Testing::require(ticked.has_value());
Void::Testing::expect(*ticked);
// Advance past renewed 30s TTL. Resolve must logically filter expired
// record even before reap_expired() runs.
Void::Testing::require(clock.advance(30s).has_value());
auto snap_expired = catalog.resolve("auth");
Void::Testing::require(snap_expired.has_value());
Void::Testing::expect(snap_expired->records.empty());
// Renewal after expiry fails with Expired.
auto late_renew = reg1->renew();
Void::Testing::expect(!late_renew.has_value());
Void::Testing::expect_eq(
late_renew.error().code().value,
static_cast<std::int32_t>(DiscoveryErrorCode::Expired));
Void::Testing::expect_eq(catalog.reap_expired(), 1ULL);
// Unleased registration stays alive indefinitely until RAII release.
{
auto unleased = catalog.register_local(
make_record("auth", "node-perm", "10.0.1.9", 9009),
LeasePolicy::unleased());
Void::Testing::require(unleased.has_value());
Void::Testing::require(clock.advance(std::chrono::hours{24}).has_value());
auto s = catalog.resolve("auth");
Void::Testing::require(s.has_value());
Void::Testing::require(s->records.size() == 1U);
Void::Testing::expect_eq(s->records[0].instance,
std::string{"node-perm"});
}
auto after_release = catalog.resolve("auth");
Void::Testing::require(after_release.has_value());
Void::Testing::expect(after_release->records.empty());
}
Void::Testing::Test discovery_watch_overflow_resync_self_cancel_and_self_join()
{
using namespace Void::Discovery;
CatalogLimits limits{};
limits.max_events_per_watch = 2;
Catalog catalog{CatalogOptions{.limits = limits}};
std::vector<WatchEvent> events;
auto wh = catalog.watch(
"billing", 0,
[&](WatchEvent ev) { events.push_back(std::move(ev)); },
WatchOptions{.dispatch_mode = WatchDispatchMode::Manual});
Void::Testing::require(wh.has_value());
// Initial snapshot queued (1 event).
Void::Testing::expect_eq(wh->pending_events(), 1ULL);
// Push 3 rapid updates without delivering -> queue cap 2 overflows and
// coalesces into an explicit ResyncRequired event carrying latest snapshot.
auto r1 = catalog.register_local(make_record("billing", "b-1"));
auto r2 = catalog.register_local(make_record("billing", "b-2"));
auto r3 = catalog.register_local(make_record("billing", "b-3"));
Void::Testing::require(r1.has_value());
Void::Testing::require(r2.has_value());
Void::Testing::require(r3.has_value());
Void::Testing::expect_eq(wh->pending_events(), 1ULL);
Void::Testing::expect_eq(wh->deliver_all(), 1ULL);
Void::Testing::require(events.size() == 1U);
Void::Testing::expect(events[0].kind == WatchEventKind::ResyncRequired);
Void::Testing::require(events[0].snapshot.has_value());
Void::Testing::expect_eq(events[0].snapshot->records.size(), 3ULL);
// Provider generation reset emits explicit ResyncRequired.
auto reset = catalog.replace_static(
{make_record("billing", "b-static")}, true);
Void::Testing::require(reset.has_value());
Void::Testing::expect_eq(catalog.provider_generation(), 2ULL);
Void::Testing::expect_eq(wh->deliver_all(), 1ULL);
Void::Testing::require(events.size() == 2U);
Void::Testing::expect(events[1].kind == WatchEventKind::ResyncRequired);
Void::Testing::expect_eq(events[1].provider_generation, 2ULL);
// Self-cancel and self-join diagnosis inside a callback (on Executor mode).
Void::Async::ManualExecutor exec{};
WatchHandle* self_ptr = nullptr;
bool self_join_diagnosed = false;
auto self_watch = catalog.watch(
"billing", 0,
[&](WatchEvent) {
if (self_ptr != nullptr) {
auto jr = self_ptr->join();
self_join_diagnosed =
!jr.has_value() &&
jr.error().code().value ==
static_cast<std::int32_t>(DiscoveryErrorCode::SelfJoin);
self_ptr->cancel();
}
},
WatchOptions{
.dispatch_mode = WatchDispatchMode::Executor,
.executor = &exec,
});
Void::Testing::require(self_watch.has_value());
self_ptr = &(*self_watch);
Void::Testing::expect(exec.drain() >= 1U);
Void::Testing::expect(self_join_diagnosed);
Void::Testing::expect(!self_watch->active());
Void::Testing::expect(self_watch->join().has_value());
Void::Testing::expect(catalog.shutdown_and_join().has_value());
}
Void::Testing::Test discovery_freshness_policy_and_selectors()
{
using namespace Void::Discovery;
Catalog catalog{};
auto pub = catalog.replace_static({
make_record("search", "s-1", "10.0.2.1", 8080, 3),
make_record("search", "s-2", "10.0.2.2", 8080, 1),
});
Void::Testing::require(pub.has_value());
catalog.set_provider_health(
Freshness::Stale,
make_discovery_error(DiscoveryErrorCode::Stale, "quorum lost"));
auto strict = catalog.resolve("search", ResolvePolicy{.allow_stale = false});
Void::Testing::expect(!strict.has_value());
auto stale_ok =
catalog.resolve("search", ResolvePolicy{.allow_stale = true});
Void::Testing::require(stale_ok.has_value());
Void::Testing::expect(stale_ok->freshness == Freshness::Stale);
Void::Testing::expect(stale_ok->provider_error.has_value());
// Weighted round-robin delivers 3:1 ratio deterministically.
WeightedRoundRobinSelector rr{};
std::size_t s1_count = 0;
std::size_t s2_count = 0;
for (int i = 0; i < 8; ++i) {
auto picked = rr.select(*stale_ok);
Void::Testing::require(picked.has_value());
if (picked->instance == "s-1") {
++s1_count;
} else {
++s2_count;
}
}
Void::Testing::expect_eq(s1_count, 6ULL);
Void::Testing::expect_eq(s2_count, 2ULL);
// Affinity selector is deterministic across repeated queries.
auto a1 = AffinitySelector::select(*stale_ok, "tenant-42");
auto a2 = AffinitySelector::select(*stale_ok, "tenant-42");
Void::Testing::require(a1.has_value());
Void::Testing::require(a2.has_value());
Void::Testing::expect_eq(a1->instance, a2->instance);
}
@@ -0,0 +1,93 @@
#include <Void/DiscoveryRpc/EndpointAdapter.hpp>
#include <Void/RPC/Rpc.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
Void::Testing::Test discovery_rpc_identity_preserving_refresh_and_roundtrip()
{
using namespace Void::Discovery;
using namespace Void::DiscoveryRpc;
Void::RPC::Server server{};
static constexpr Void::RPC::MethodId kEchoMethod{100U, 1U};
auto reg = server.bind(
Void::RPC::MethodDescriptor{
.id = kEchoMethod,
.service_name = "echo",
.method_name = "ping",
.schema_version = 1,
},
[](const Void::RPC::CallContext& ctx, Void::RPC::OwnedBytes req)
-> Void::Result::Result<Void::RPC::OwnedBytes> {
std::string auth_seen;
for (const auto& m : ctx.metadata) {
if (m.key == "void-expected-authority") {
auth_seen = m.value;
}
}
Void::RPC::OwnedBytes out = std::move(req);
for (char c : auth_seen) {
out.push_back(static_cast<std::byte>(c));
}
return out;
});
Void::Testing::require(reg.has_value());
Void::Testing::require(server.start().has_value());
Catalog catalog{};
EndpointRecord rec{};
rec.service = "echo";
rec.instance = "echo-1";
rec.endpoint.scheme = "http";
rec.endpoint.host = "127.0.0.1";
rec.endpoint.port = server.bound_port();
rec.endpoint.expected_tls_name = "echo.internal";
rec.weight = 1;
Void::Testing::require(catalog.replace_static({rec}).has_value());
EndpointResolverClient client{
catalog,
EndpointResolverOptions{
.service = "echo",
.expected_tls_name = "echo.internal",
.require_tls = false,
},
};
Void::RPC::OwnedBytes payload{std::byte{'o'}, std::byte{'k'},
std::byte{':'}};
auto resp = client.call(kEchoMethod, std::move(payload));
Void::Testing::require(resp.has_value());
const std::string reply{
reinterpret_cast<const char*>(resp->data()), resp->size()};
Void::Testing::expect_eq(reply, std::string{"ok:echo.internal"});
// TLS enforcement rejects non-HTTPS downgrade and mismatched identity.
EndpointResolverClient tls_client{
catalog,
EndpointResolverOptions{
.service = "echo",
.expected_tls_name = "echo.internal",
.require_tls = true,
},
};
auto downgrade = tls_client.select_endpoint();
Void::Testing::expect(!downgrade.has_value());
Void::Testing::expect_eq(
downgrade.error().code().value,
static_cast<std::int32_t>(DiscoveryErrorCode::TlsIdentityMismatch));
// Identity mismatch on HTTPS refresh also fails closed.
rec.endpoint.scheme = "https";
rec.endpoint.expected_tls_name = "spoofed.evil";
Void::Testing::require(catalog.replace_static({rec}).has_value());
auto mismatch = tls_client.select_endpoint();
Void::Testing::expect(!mismatch.has_value());
Void::Testing::expect_eq(
mismatch.error().code().value,
static_cast<std::int32_t>(DiscoveryErrorCode::TlsIdentityMismatch));
server.shutdown();
}